Number.prototype.toPrecision
Formats a number with a given number of significant digits.
Available since: ES3
Syntax
number.toPrecision(precision)Parameters
| Parameter | Type | Description |
|---|---|---|
| precision | number | The 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.00123Large numbers get exponential notation:
console.log((123456).toPrecision(2));Output:
1.2e+5Notes
Significant digits are counted from the first non-zero one. To set the number of digits after the point use toFixed().
See also
- Number.prototype.toFixed — Formats a number with a given number of decimal places.
- Math.round — Rounds a number to the nearest integer.
In the tutorial
- Numbers — Numbers in JavaScript — integers and fractions, rounding, the Math object, toFixed and the special values Infinity and NaN.