The toPrecision() function in Javascript is used to format numbers to a specific precision or length. If the formatted number requires more digits than the original number, decimals and null values are also added to create the specified length. Let's take a look at the specific use of the toPrecision function.
Let’s first take a look at the basic syntax of the toPrecision function
number .toPrecision(value)
toPrecision function accepts a single parameter value, this parameter is optional , which represents the number of significant digits the user needs in a formatted number.
Let’s look at a specific example
No parameters are passed in the toPrecision() method:If no parameters are passed to the toPrecision() function, the formatted number will be exactly the same as entering a number. However, it will be represented as a string rather than a number.
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision()); </script> </body> </html>
The output result is: 213.45689
Pass parameters in the toPrecision() function: If the precision passed to the toPrecision() function If the length is less than the original number, the number will be rounded to that precision.
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(4)); </script> </body> </html>
The output result is: 213.5
Pass a parameter, which will cause a null value to appear in the output: If passed to toPrecision () function has a precision length greater than the original number, appends a zero value to the input number to satisfy the specified precision.
The code is as follows
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> var num=213.45689; document.write(num.toPrecision(12)+"<br>"); var num2 = 123; document.write(num2.toPrecision(5)); </script> </body> </html>
The output result is as follows
213.456890000 123.00
This article ends here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website ! ! !
The above is the detailed content of How to use toPrecision function. For more information, please follow other related articles on the PHP Chinese website!