Home > Article > Web Front-end > How to convert numeric value to string in javascript
Method: 1. toString() method, the syntax is "numeric value.toString()"; 2. toFixed() method, which can convert the numerical value into a string and display the specified number of digits after the decimal point; 3. toExponential() method; 4. toPrecision() method.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1, Use toString() method
When calling toString() method for a simple value, JavaScript will automatically They are encapsulated as objects, and then the toString() method is called to obtain the string representation of the object.
var a = 123456; a.toString(); console.log(a); //返回字符串“123456”
When using the toString() method to convert a value to a string, decimal places cannot be retained. This is undoubtedly inconvenient for outputting display numbers in professional fields such as currency formatting and scientific notation. To this end, JavaScript provides three dedicated methods, toFixed(), toExponential(), and toPrecision(), which are introduced below.
2, use toFixed() method
toFixed() can convert the value into a string , and displays the specified number of digits after the decimal point.
var a = 10; console.log(a.toFixed(2)); //返回字符串“10.00” console.log(a.toFixed(4)); //返回字符串“10.0000”
3. Use the toExponential() method
The toExponential() method is specifically used to convert numbers into strings in scientific notation.
var a = 123456789; console.log(a.toExponential(2)); //返回字符串“1.23e+8” console.log(a.toExponential(4)); //返回字符串“1.2346e+8”
The parameters of the toExponential() method specify the number of decimal places to retain. Omitted parts are rounded off.
4. Use toPrecision() method
The toPrecision() method is similar to the toExponential() method, but it can specify the number of significant digits instead of specifying decimals number of digits.
var a = 123456789; console.log(a.toPrecision(2)); //返回字符串“1.2e+8” console.log(a.toPrecision(4)); //返回字符串“1.235e+8”
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to convert numeric value to string in javascript. For more information, please follow other related articles on the PHP Chinese website!