Use toFixed() Method or toPrecision() Method to get float precision of given number in JavaScript. The toFixed() method converts the number into a string, keeping the specified number of digits after the point.
number.toFixed(digits)
The toPrecision() Method converts the number into a string, keeping the total number of digits of the value as specified and rounding them to the nearest number.
number.toPrecision(precision)
JavaScript float precision example
Simple example code Floating point number precision.
Using toFixed()
<!doctype html>
<head>
<script>
pi = 3.14959265359;
res1 = pi.toFixed(2);
res2 = pi.toFixed(5);
console.log(res1);
console.log(res2);
</script>
</head>
<body>
</body>
</html>
Output:
Using toPrecision() Method:
<script>
pi = 3.14959265359;
res1 = pi.toPrecision(2);
res2 = pi.toPrecision(5);
console.log(res1);
console.log(res2);
</script>
Output: 3.1
3.1496
Do comment if you have any doubts or suggestions on this JS float precision topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version