The Javascript Number toPrecision()
method format Number object to string by the specified precision.
numObj.toPrecision([precision])
Parameter | Optional | Meaning |
---|---|---|
precision | Optional | An integer specifying the number of significant digits. |
If the precision argument is omitted, it behaves as Number.prototype.toString()
.
If the precision argument is a non-integer value, it is rounded to the nearest integer.
The toPrecision()
method returns either the fixed or the exponential representation of a number, depending on which makes the most sense.
This method takes one argument, which is the total number of digits to use to represent the number, not including exponents.
let num = 99; /*from w w w . j a v a 2s . com*/ console.log(num.toPrecision(1)); // "1e+2" console.log(num.toPrecision(2)); // "99" console.log(num.toPrecision(3)); // "99.0"
In this example, the first task is to represent the number 99 with a single digit, which results in "1e+2".
The toPrecision()
method determines whether to call toFixed()
or toExponential()
based on the numeric value.
Using toPrecision()
let numObj = 12345.123456 console.log(numObj.toPrecision());/*from w ww . j av a2 s .c om*/ console.log(numObj.toPrecision(5)); console.log(numObj.toPrecision(2)); console.log(numObj.toPrecision(1)); numObj = 0.000123 console.log(numObj.toPrecision()); console.log(numObj.toPrecision(5)); console.log(numObj.toPrecision(2)); console.log(numObj.toPrecision(1)); console.log((1234.5).toPrecision(2))