Number.prototype.toPrecision()
The one people reach for when they wanted toFixed. It counts digits from the left of the number, so the same argument produces wildly different output depending on magnitude.
Demo
Significant digits are counted from the first non-zero digit, so 123.456 to four gives '123.5' — three before the point and one after. The second case is the surprise: asking for two significant digits from 123456 cannot be written in fixed notation without implying six digits of precision, so the method switches to '1.2e+5'. Formatting code that expected plain digits gets exponential notation instead. The small-fraction case shows the leading zeros are not counted as significant, and the fourth shows zeros are padded on to reach the requested count.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| digits | number | no (as many as needed) | Significant digits, 1 to 100. Omitted entirely, the method behaves exactly like toString. Outside the range it throws RangeError. |
Return value
string — A string with the given number of SIGNIFICANT digits — counted from the first non-zero digit, not from the decimal point. Falls back to exponential notation when fixed notation would need more digits than requested.
Common patterns
const shown = measurement.toPrecision(3);
const shown = price.toFixed(2);
const s = n.toPrecision(3); const safe = s.includes("e") ? n.toFixed(2) : s;
Examples
Pitfalls
(123456).toPrecision(2)
(123456).toFixed(2)
(123456).toPrecision(2)
const s = n.toPrecision(2); s.includes("e") ? n.toFixed(0) : s
(1).toPrecision(2) + 1
Number((1).toPrecision(2)) + 1
(123.456).toPrecision()
(123.456).toPrecision(4)
When to use
- Scientific and engineering output, where significant figures are standard
- Normalising numbers of wildly different magnitudes to the same information content
- Deliberately producing exponential notation for very large or small values
- Money and UI numbers → toFixed, or Intl.NumberFormat
- You need exponential always → toExponential
- You need a number back → this returns a string
- Locale-aware output → toLocaleString
Notes
FAQ
toFixed for anything with a fixed unit — money, percentages, measurements shown to a set number of decimals. toPrecision when the significant information content matters regardless of magnitude, which is mostly scientific work.
(0.001234).toFixed(2); // '0.00' — all detail lost (0.001234).toPrecision(2); // '0.0012' — two significant digits