Javascript Reference - JavaScript toPrecision() Method








The toPrecision() method formats a number to a specified length.

The toPrecision() method returns either the fixed or the exponential representation of a number. This method takes the total number of digits to represent the number as the argument.


var num = 99; 
console.log(num.toPrecision(1)); //"1e+2" 
console.log(num.toPrecision(2)); //"99" 
console.log(num.toPrecision(3)); //"99.0" 

The code above generates the following result.

Browser Support

toPrecision Yes Yes Yes Yes Yes




Syntax

var v = number.toPrecision(x)

Parameter Values

Parameter Description
x Optional. The number of digits in the returned string. If omitted, it returns the entire number without any formatting.

Return Value

A String type value representing a number formatted to the specified precision.

Example

The following code shows how to format a number into a specified length.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!--from  w w w . j  a  v  a2s  .com-->
<p id="demo"></p>

<script>
function myFunction() {
    var num = 12.3456;
    document.getElementById("demo").innerHTML = num.toPrecision(2);
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to format a number between 0 and 1.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!-- w  w  w.j a  v  a2s . c o m-->
<p id="demo"></p>

<script>
function myFunction() {
    var num = 0.001234567;
    var a = num.toPrecision();
    var b = num.toPrecision(2);
    var c = num.toPrecision(3);
    var d = num.toPrecision(10);

    var n = a + "<br>" + b + "<br>" + c + "<br>" + d;

    document.getElementById("demo").innerHTML=n;
}
</script>

</body>
</html>

The code above is rendered as follows: