Number.prototype.toPrecision()
Returns a string representing the number to the specified number of significant digits.
Syntax
num.toPrecision(precision) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
precision | number | No | Number of significant digits (1 to 100). If omitted, behaves like toString. |
Returns
string — A string with the requested number of significant digits.
Throws
RangeError— precision is outside 1 to 100.
Examples
console.log((123.456).toPrecision(4));
Output
123.5
console.log((0.000123).toPrecision(2));
Output
0.00012
Notes
Switches to exponential notation when the precision cannot represent the
number in fixed form. Returns a string. Counts significant digits, not decimal
places (unlike `toFixed`).
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |