<script>
var str=1445.32678
document.write(str.toPrecision(6)); // Output 1445.33
</script>
The input parameter is optional, if not given then entire number is returned. It must be between 1 and 100 <script>
var str=1445.32678
document.write(isNaN(str.toPrecision(10))); // Output false
</script>
Here are some examples to explain toPrecision math function.
<script language='JavaScript' type='text/JavaScript'><br />
<!--<br />
var my_val=11.257;<br />
document.write (my_val.toPrecision(2)); // output 11<br />
document.write ("<br>----<br>");<br />
<br />
var my_val=11.257;<br />
document.write (my_val.toPrecision(5)); // output 11.257<br />
document.write ("<br>----<br>");<br />
<br />
var my_val=11.257;<br />
document.write (my_val.toPrecision(6)); // output 11.2570<br />
document.write ("<br>----<br>");<br />
<br />
var my_val=1.1257;<br />
document.write (my_val.toPrecision(3)); // output 1.13<br />
document.write ("<br>----<br>");<br />
<br />
<br />
var my_val=11257;<br />
document.write (my_val.toPrecision(3)); // output 1.13e+4<br />
document.write ("<br>----<br>");<br />
<br />
var my_val=11257;<br />
document.write (my_val.toPrecision(2)); // output 1.1e+4<br />
document.write ("<br>----<br>");<br />
//--><br />
</script>
While using any data coming from a text box or any other sources, we have to use parseInt or parseFloat functions to convert the data from string to integer or float before using toFixed function.
We can check different values by using a demo script which returns data after executing toFixed function from the user entered data. By using toPrecision function we can manage the total length.