JavaScript Number toPrecision() method

Definition and usage

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

This method formats the significant digits of the number.

instance

Example 1

format the number to a specified length:

let num = 13.3714;
let n = num.toPrecision(2);

try it yourself

Example 2

format the decimal:

let num = 0.001658853;
num.toPrecision(2);
num.toPrecision(3);
num.toPrecision(10);

try it yourself

Example 3

format the number to a specified length:

let num = 13.3714;
num.toPrecision(2);
num.toPrecision(3);
num.toPrecision(10);

try it yourself

Example 4

unformatted:

let num = 13.3714;
num.toPrecision();

try it yourself

syntax

number.toPrecision(precision)

parameter

parameter description
precision

optional. number of digits.

values between 1 and 21 (including 1 and 21).

if omitted, the number without any format is returned.

return value

type description
string format the number to the specified precision.

technical details

return value

return the string representation of Number, including precision significant digits.

if precision sufficiently large to include all the digits of the integer part of Number, then the returned string will use fixed-point notation.

otherwise, use exponential notation, that is, one digit before the decimal point and precision1 digit.

if necessary, the number will be rounded or padded with zeros.

thrown

exception description
RangeError

when precision an exception is thrown when it is too small or too large.

values between 1 and 21 do not cause this exception.

some implementations support a wider or narrower range of values.

TypeError an exception is thrown if the object called this method is not a Number.

browser support

toPrecision() is a feature of ECMAScript3 (ES3).

All browsers fully support ES3 (JavaScript 1999):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support