Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Number.prototype.toPrecision

Formats a number with a given number of significant digits.

Available since: ES3

Syntax

number.toPrecision(precision)

Parameters

ParameterTypeDescription
precisionnumberThe number of significant digits, from 1 to 100.

Return value

stringThe number as a string with that many significant digits.

Examples

Three significant digits:

console.log((123.456).toPrecision(3));
console.log((0.0012345).toPrecision(3));

Output:

123
0.00123

Large numbers get exponential notation:

console.log((123456).toPrecision(2));

Output:

1.2e+5

Notes

Significant digits are counted from the first non-zero one. To set the number of digits after the point use toFixed().

See also

In the tutorial

  • Numbers — Numbers in JavaScript — integers and fractions, rounding, the Math object, toFixed and the special values Infinity and NaN.

Thanks for reading!

Donate to the site — we work hard for you.