# toPrecision Math function

``````<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

WE can use toPrecision math function in JavaScript where we want to convert numbers to a fixed length.
If required the given number is converted to exponential notation to match the space or length specified. This is a common way to where we want numbers to be of definite length.

## Return value is number

We can use isNaN to check the output.
``````<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>``````

Demo of toPrecision() function

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. To manage only decimal places we can use toFixed function.

Format a decimal number to number of places

Subscribe to our YouTube Channel here

## Subscribe

* indicates required
Subscribe to plus2net

plus2net.com

Post your comments , suggestion , error , requirements etc here