Number toPrecision() Method - Javascript Number

Javascript examples for Number:toPrecision

Description

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

Parameter Values

Parameter Description
x Optional. The number of digits. If omitted, it returns the entire number

Return Value:

A String, representing a number formatted to the specified precision

The following code shows how to Format a number into a specified length:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {//from  ww w  .j av  a 2 s. c  om
    var num = 1.001652234;
    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>

Related Tutorials