In JavaScript's value type conversion, the most common occurrence is the mutual conversion between two types of values, string and number.
You can convert it into a string by calling the 4 functions of the number value (in fact, JS automatically converts the number value into the Number object and the 4 functions of the Number class after it automatically converts the number value into a Number object):
1.toString().
2.toFixed().
3.toExponential().
4.toPrecision().
toString()
The toString() method can be called on the number value to convert it into a string. The toString() function accepts a positive integer between 2 and 36 as a parameter, and its function is to define the numerical value; if the parameter is missing, the toString() function represents the corresponding numerical value in decimal.
The code copy is as follows:
var a = 42;
console.log(a.toString(2));//101010
console.log(a.toString());//42
console.log("0x" + a.toString(16));//0x2a
var b = 0xff;
console.log(b.toString());//255
toFixed()
The toFixed() function accepts an integer as a parameter, and the parameter acts as the exact number of digits after the specified decimal point. The parameters accepted by the toFixed() function can also be negative (although less used), and when the parameter is negative, the integer part of the value will lose precision. When adjusting numeric values using the toFixed() function, JavaScript follows the principle of rounding.
The code copy is as follows:
var x = 17.38;
console.log(x.toFixed(0));//17
console.log(x.toFixed(1));//17.4
console.log(x.toFixed(4));//17.380
console.log(x.toFixed(-1));//20
toExponential()
The toExponential() function can be used to convert numeric values into scientific notation. The toExponential() function accepts a non-negative integer as a parameter (if this parameter is negative, a RangeError is thrown) as the accuracy of the scientific notation method. Like the toFixed() function, the toExponential() function follows the rounding principle when adjusting numerical values.
The code copy is as follows:
var y = 17951.38596
console.log(y.toExponential(1));//1.8e+4
console.log(y.toExponential(0));//2e+4
toPrecision()
The toPrecision() function takes a positive integer as a parameter (if the parameter is 0 or negative, the program will throw a RangeError) and use it as the exact number of digits of the value (including the integer part and the decimal part). If the exact number of digits is less than the integer part of the value, the value will be converted to be expressed in scientific notation. Like the toFixed() function, the toPrecision() function follows the principle of rounding when adjusting numerical values.
The code copy is as follows:
var z = 17951.38596;
console.log(z.toPrecision(8));
console.log(z.toPrecision(3));