Skip to content
Latest: Publish JavaScript Packages to NPM Like a Pro!

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.

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.

Below are examples of the toPrecision() method.

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

Try Editing It

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

Try Editing It

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

Try Editing It

Format 2703.5941 to precisely eleven digits

Section titled “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.

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.

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

Section titled “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.