JavaScript toPrecision is used to format a number to a specific precision or length. Basically, it’s a specified length of number.
Note: JS toPrecision method returns a string representing the Number object to the specified precision/length.
Syntax
number.toPrecision(x)
Example of JavaScript toPrecision method
Example of How to JavaScript Format a number into a specified length.
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var num = 98.9614;
var n = num.toPrecision(2);
alert(n);
</script>
</body>
</html>
Output:
What if JavaScript decimal precision more than the actual number?
At this condition a decimal point and nulls (zero) are added to create the specified length. See below example:-
<script language="JavaScript">
var num = 98.33;
var n = num.toPrecision(7);
alert(n);
</script>
Output: 98.33000
Do comment if you have any doubts and suggestions on this tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version