JavaScript Number toPrecision() Method

Definition and usage

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

This method formats the significant digits of the number.

Example

Example 1

Formats the number to the specified length:

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

Try it yourself

Example 2

Formats the decimal:

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

Try it yourself

Example 3

Formats the number to the 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, returns the number without any formatting.

Return value

Type Description
String Formats the number to the specified precision.

Technical details

Return value

Returns 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 too small or too large.

Values between 1 and 21 will not trigger this exception.

Some implementations support values in a wider or narrower range.

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

Browser support

toPrecision() It 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