Precision means accurate, toPrecision()
is a method in JavaScript, in mathematics precision method is appliceble for while converting. Converting the decimals to approximate and accurate values.
In JavaScript, by using toPrecision()
method we can format a number to a specified length.
<p>Click the below button to format into 3 digit specified length</p> <input type="button" value="Format" onclick="Function()" /> <p id="myId"></p> <script> function Function() { var a = 1.74562; var r = a.toPrecision(3); document.getElementById("myId").innerHTML = r; } </script>
We need to format the length of the decimal number in variable a
to 3 digit approximate decimal number, for that we are using toPrecision()
method. Onclick of the button "Format" in the HTML code fires the Function() in the <script>
block, at the same time toPrecision(3)
method formats the length of the decimal and return the specified length number as output.
OUTPUT
<p>Click the below button to format into 3 digit specified length</p> <input type="button" value="Format" onclick="Function()" /> <p id="myId"></p> <script> function Function() { var a = 1.74562; var r =a.toPrecision() + "</br>" + a.toPrecision(1) + "</br>" + a.toPrecision(2) + "</br>" + a.toPrecision(3) + "</br>" + a.toPrecision(4) + "</br>" + a.toPrecision(5) + "</br>" + a.toPrecision(6) + "</br>" + a.toPrecision(7) + "</br>" ; document.getElementById("myId").innerHTML = r; } </script>
Format into different lengths of same number
Onclick of the button gives the different format lengths of the same decimal number as per the input value.
OUTPUT
<p>Click the below button to format into 3 digit specified length</p> <input type="button" value="Format" onclick="Function()" /> <p id="myId"></p> <script> function Function() { var a = 0.0758642; var r =a.toPrecision() + "</br>" + a.toPrecision(1) + "</br>" + a.toPrecision(2) + "</br>" + a.toPrecision(3) + "</br>" + a.toPrecision(4) + "</br>" + a.toPrecision(5) + "</br>" + a.toPrecision(6) + "</br>" + a.toPrecision(7) + "</br>" ; document.getElementById("myId").innerHTML = r; } </script>
Formating the length of nano values
We are formating the length of nano value (0.0758642), nano values are vey samll values which starts like 0.0014512... Onclick of the button returns the formatted length digits as per the input values.
OUTPUT
Views: 4476 | Post Order: 89