Number.prototype.toFixed()
The standard way to format a number for display, and a reliable source of confusion: it returns a string, and its rounding follows the binary value rather than the decimal one you wrote.
Demo
The first case is the everyday use. The second and third are the ones that generate bug reports: 1.005 formatted to two places gives '1.00', not '1.01'. Nothing is broken — the literal 1.005 cannot be represented exactly in binary floating point, and the value actually stored is very slightly BELOW 1.005, so rounding down is correct for the number that exists. The same applies to 1.045. Note also that the output is padded with zeros to reach the requested width, and that every result here is a string.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| digits | number | no (0) | Decimal places to show, 0 to 100. Anything outside that range throws RangeError. Trailing zeros are added to reach the count. |
Return value
string — A STRING with exactly the requested number of decimal places. Not a number — arithmetic on the result concatenates instead of adding.
Common patterns
el.textContent = `$${price.toFixed(2)}`;
const cents = 1005; const shown = (cents / 100).toFixed(2);
new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(price);
Examples
Pitfalls
(1).toFixed(2) + 1
Number((1).toFixed(2)) + 1
(1.005).toFixed(2)
(Math.round(1.005 * 1000) / 10).toFixed(0)
(1e21).toFixed(2)
new Intl.NumberFormat().format(1e21)
(1234.5).toFixed(2)
(1234.5).toLocaleString('de-DE', {minimumFractionDigits: 2})
When to use
- Formatting a number for display with a fixed number of decimals
- Producing a consistent string for a log or a fixed-width report
- Quick output where locale does not matter
- Money arithmetic → integer minor units, or a decimal library
- User-facing numbers → toLocaleString or Intl.NumberFormat
- You need a number back → you probably wanted Math.round
- Significant digits rather than decimal places → toPrecision
Notes
FAQ
Because 1.005 is not the number you think it is. Written as a double it is approximately 1.00499999999999989, which correctly rounds to 1.00. Multiply it by 1000 and you get 1004.9999999999999 — the shortfall is visible.
1.005 * 1000; // 1004.9999999999999