The toString method is "to String (string)", which is the method used when "converting to a string". In How to convert numeric value to string using toString in JavaScript, all values are divided into data types such as numeric values, strings, and arrays. toString method is used when converting a non-string to a string.
How to use toString method?
How to get the number of digits in a number
If you want to get a big number, such as 100000000000000000000, you can get it if you use length Numerical, but length is a method used by strings and cannot be used by numbers.
var num = 10000000000000; console.log(num.length);
The execution result is as follows:
undefiened
Therefore, the number of characters can be obtained by converting the numerical value to a string.
Let’s use toString()
var num = 10000000000000; var digits = num.toString().length; console.log(digits + "位数");
The execution result is:
14位数
In this way, we use the toString method to convert non-strings (such as numbers) into characters string.
When converting a numeric value to a string, you can also perform base conversion at the same time.
The code is as follows
var num = 10; var bin_converted = num.toString(2); var hex_converted = num.toString(16); console.log("10的二进制是:" + bin_converted); console.log("10的十六进制是:" + hex_converted);
The execution results are as follows:
10的二进制是:1010 10的十六进制是:a
In addition to numbers, dates (Date), arrays (Array), objects = associative arrays ( Object), etc. can also be converted to strings.
How to convert date to string?
You can also use the toString method to convert the date (Date object) into a string
var date = new Date(); // 今天的日期 console.log("今天:" + date.toString()); console.log("今天:" + date.toISOString());
The execution results are as follows:
今天:Sat Jan 19 2019 15:27:22 GMT+0800 (中国标准时间) 今天:2019-01-19T07:27:22.656Z
Note: The toISOString method is used to output in ISO standard format
How to convert an array (Array) to a string?
Array can also be converted to string and output.
var array = ["苹果","橙子","香蕉","葡萄","柚子"] console.log("喜欢的水果是:" + array.toString());
The execution result is as follows:
喜欢的水果是:苹果,橙子,香蕉,葡萄,柚子
Note: Since it is a string output by the toString method, it can be added together with other strings.
This article ends here. For more exciting content, you can pay attention to the relevant column tutorials on the php Chinese website! ! !
The above is the detailed content of How to convert numeric value to string using toString in JavaScript. For more information, please follow other related articles on the PHP Chinese website!