Skip to main content

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.

note

toPrecision() is sometimes written as Number.prototype.toPrecision() because it is a method of the Number object's prototype property.

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.

note
  • toPrecision() returns a string value.
  • toPrecision() does not change the original number.
  • Browsers round the returned value if necessary.
  • Browsers add extra zeros if necessary to make up the totalDigits.
  • The totalDigits argument must be an integer between 1 and 100 inclusive. Otherwise, browsers will throw an Uncaught RangeError.
  • The computer returns an exponential notation whenever it does a division operation on the given number.

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.

Overview

This article discussed what toPrecision() is. We also used examples to see how it works.

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Tweet this article