The Number toPrecision() method

By

Learn how the JavaScript Number toPrecision() method returns a string representing a number to a given number of significant digits, padding or rounding it.

~~~

toPrecision() returns a string representing the number to the given number of significant digits:

new Number(21.2).toPrecision(0) //RangeError! argument must be between 1 and 100
new Number(21.2).toPrecision(1) //2e+1 (= 2 * 10^1 = 2)
new Number(21.2).toPrecision(2) //21
new Number(21.2).toPrecision(3) //21.2
new Number(21.2).toPrecision(4) //21.20
new Number(21.2).toPrecision(5) //21.200

Note that it counts significant digits, not decimal places. 21.2 has three significant digits, so asking for 4 pads it with a zero, and asking for 2 rounds it down to 21.

You don’t need the Number object wrapper. The method works on any number:

(21.2).toPrecision(3) //'21.2'

How is it different from toFixed()?

toFixed() counts digits after the decimal point. toPrecision() counts all significant digits:

const num = 123.456

num.toFixed(2) //'123.46'
num.toPrecision(2) //'1.2e+2'

Reach for toFixed() when formatting prices or measurements, where the decimal places matter. Reach for toPrecision() when the overall precision matters, like in scientific or statistical values.

It returns a string

Both methods return a string, not a number. This is the pitfall that bites people:

const rounded = (3.14159).toPrecision(3) //'3.14'

rounded + 1 //'3.141', string concatenation!

Adding a number to the result concatenates instead of summing. The fix is to convert back before doing math:

Number(rounded) //3.14, a number again

When does it switch to exponential notation?

If the number has more integer digits than the precision you ask for, the result uses exponential notation:

(1234.5).toPrecision(2) //'1.2e+3'
(1234.5).toPrecision(6) //'1234.50'

Two significant digits can’t represent 1234, so it becomes 1.2 × 10³. That’s also why toPrecision(1) returned '2e+1' in the first example: one digit can’t hold 21.

If you’re displaying the result to users, check for the e or pick a precision large enough to avoid it.

Small numbers stay in regular notation much longer. (0.000123).toPrecision(2) returns '0.00012', no exponent needed.

The valid range

The argument must be between 1 and 100, or you get a RangeError. That’s what happens with toPrecision(0) in the first example.

Called with no argument at all, toPrecision() behaves like toString() and returns the full number as a string.

~~~

Related posts about js: