Skip to content
Latest: The updated version of the Creating NPM Package (React JavaScript) book is out

toPrecision() Method – How to Format Number to Precise Length

toPrecision() formats a number to a precise length of digits and returns the result as a string.

Syntax of the toPrecision() Method

toPrecision() accepts only one optional argument. Here is the syntax:

number.toPrecision(totalDigits);

The totalDigits argument specifies the number of digits into which browsers should format the given number. If omitted, browsers will return the number as a string without formatting its length.

Examples of the toPrecision() Method

Below are examples of the toPrecision() method.

Format 2703.5941 to precisely five digits

const number = 2703.5941;
number.toPrecision(5);
// The invocation above will return: 2703.6

Try Editing It

Format 2703.5941 to precisely six digits

const number = 2703.5941;
number.toPrecision(6);
// The invocation above will return: 2703.59

Try Editing It

Format 2703.5941 to precisely four digits

const number = 2703.5941;
number.toPrecision(4);
// The invocation above will return: 2704

Try Editing It

Format 2703.5941 to precisely eleven digits

const number = 2703.5941;
number.toPrecision(11);
// The invocation above will return: 2703.5941000

Try Editing It

The snippet above added extra zeros to make up the totalDigits.

Format 2703.5941 to precisely two digits

const number = 2703.5941;
number.toPrecision(2);
// The invocation above will return: 2.7e+3

Try Editing It

The computer returned an exponential value because it divided the number by 1000.

Format 2703.5941 to precisely one digit

const number = 2703.5941;
number.toPrecision(1);
// The invocation above will return: 3e+3

Try Editing It

The computer returned an exponential value because it divided the number by 1000.

Format 2703.5941 to precisely three digits

const number = 2703.5941;
number.toPrecision(3);
// The invocation above will return: 2.70e+3

Try Editing It

The computer returned an exponential value because it divided the number by 1000.