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
Complete guide to publishing NPM Libraries with React JavaScript
Learn moreFormat 2703.5941
to precisely six digits
const number = 2703.5941;
number.toPrecision(6);
// The invocation above will return: 2703.59
Format 2703.5941
to precisely four digits
const number = 2703.5941;
number.toPrecision(4);
// The invocation above will return: 2704
Format 2703.5941
to precisely eleven digits
const number = 2703.5941;
number.toPrecision(11);
// The invocation above will return: 2703.5941000
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
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
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
The computer returned an exponential value because it divided the number by 1000
.