Use the toPrecision() method to format a number to a specific precision or length in Javascript. This method returns a string representing the Number
object to the specified precision.
toPrecision()
toPrecision(precision)
A decimal point and nulls are added (if needed), to create the specified length.
JavaScript number precision
Simple example code format a number to a specified length:
<!DOCTYPE html>
<html>
<body>
<script>
let num = 11.3714;
console.log(num.toPrecision(2));
console.log(num.toPrecision(3));
console.log(num.toPrecision(10));
</script>
</body>
</html>
Output:
More examples
function precise(x) {
return x.toPrecision(4);
}
console.log(precise(123.456)); // "123.5"
console.log(precise(0.004)); // "0.004000"
console.log(precise(1.23e5)); // "1.230e+5"
Do comment if you have any doubts or suggestions on this Js number topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version