revision:
The toPrecision() method returns a string representing the Number object to the specified precision.
A decimal point and nulls are added (if needed), to create the specified length.
toPrecision() toPrecision(precision)
Parameters:
precision : optional. An integer specifying the number of significant digits. The number of digits. If omitted, the number is returned without any formatting.
function precise(x) { return x.toPrecision(4); } console.log(precise(123.456)); // Expected output: "123.5" console.log(precise(0.004)); // Expected output: "0.004000" console.log(precise(1.23e5)); // Expected output: "1.230e+5"
<div> <p id="precision-1"> </p> <p id="precision-2"> </p> <p id="precision-3"> </p> <p id="precision-4"> </p> <p id="precision-5"> </p> <p id="precision-6"> </p> <p id="precision-7"> </p> <p id="precision-8"> </p> <p id="precision-9"> </p> <p id="precision-10"> </p> <p id="precision-11"> </p> </div> <script> let num = 5.123456; document.getElementById("precision-1").innerHTML = "number: " + num; console.log(num.toPrecision()); // '5.123456' console.log(num.toPrecision(5)); // '5.1235' console.log(num.toPrecision(2)); // '5.1' console.log(num.toPrecision(1)); // '5' document.getElementById("precision-2").innerHTML = "number toPrecision() : " + num.toPrecision(); document.getElementById("precision-3").innerHTML = "number toPrecision(5) : " + num.toPrecision(5); document.getElementById("precision-4").innerHTML = "number toPrecision(2) : " + num.toPrecision(2); document.getElementById("precision-5").innerHTML = "number toPrecision(1) : " + num.toPrecision(1); num = 0.000123; document.getElementById("precision-6").innerHTML = "number: " + num; console.log(num.toPrecision()); // '0.000123' console.log(num.toPrecision(5)); // '0.00012300' console.log(num.toPrecision(2)); // '0.00012' console.log(num.toPrecision(1)); // '0.0001' document.getElementById("precision-7").innerHTML = "number toPrecision() : " + num.toPrecision(); document.getElementById("precision-8").innerHTML = "number toPrecision(5) : " + num.toPrecision(5); document.getElementById("precision-9").innerHTML = "number toPrecision(2) : " + num.toPrecision(2); document.getElementById("precision-10").innerHTML = "number toPrecision(1) : " + num.toPrecision(1); // note that exponential notation might be returned in some circumstances console.log((1234.5).toPrecision(2)); // '1.2e+3' document.getElementById("precision-11").innerHTML = "number toPrecision(1) : " + (1234.5).toPrecision(2); </script>