JavaScript Number toPrecision() Method
The JavaScript Number toPrecision( ) method in Javascript is used to format a number to a specific precision or length. If the formatted number requires more digits than the original number then decimals and nulls are also added to create the specified length.
Syntax:
number.toPrecision(value)
The toPrecision() method is used with a number as shown in the above syntax using the ‘.’ operator. This method will format a number to a specified length.
Parameters: This method accepts a single parameter value. This parameter is also optional and it represents the value of the number of significant digits the user wants in the formatted number.
Return Value: The toPrecision() method in JavaScript returns a string in which the number is formatted to the specified precision.
Below is an example of the Number toPrecision( ) Method.
Example 1:
Javascript
<script type="text/javascript"> var num=213.45689; console.log(num.toPrecision(3)); </script> |
Output:
213
Example 2: Passing no arguments in the toPrecision() method, If no arguments are passed to the toPrecision() method then the formatted number will be exactly the same as the input number. Though, it will be represented as a string rather than a number.
Javascript
<script type="text/javascript"> var num=213.45689; console.log(num.toPrecision()); </script> |
Output:
213.45689
Example 3: Passing an argument in the toPrecision() method, If the length of precision passed to the toPrecision() method is smaller than the original number then the number is rounded off to that precision.
Javascript
<script type="text/javascript"> var num=213.45689; console.log(num.toPrecision(4)); </script> |
Output:
213.5
Example 4: Passing an argument that results in the addition of null in the output, If the length of precision passed to the toPrecision() method is greater than the original number then zeros are appended to the input number to meet the specified precision.
Javascript
<script type="text/javascript"> var num=213.45689; console.log(num.toPrecision(12)); var num2 = 123; console.log(num2.toPrecision(5)); </script> |
Output:
213.456890000 123.00
Note: If the precision specified is not between 1 and 100 (inclusive), it results in a RangeError.
We have a complete list of Javascript Number Objects methods, to check those please go through this Javascript Number Complete reference article.
Supported Browsers:
- Google Chrome 1 and above
- Internet Explorer 5.5 and above
- Firefox 1 and above
- Apple Safari 2 and above
- Opera 7 and above
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.






Please Login to comment...