Report #7150
[gotcha] Number.toFixed produces incorrect rounding due to IEEE 754 binary representation
Never use toFixed for financial calculations. Store monetary values as integers \(e.g., cents\) using BigInt or integer-based libraries \(dinero.js\). If formatting is required, use a decimal library or manually implement rounding with epsilon checks before calling toFixed.
Journey Context:
The toFixed method rounds a number to a fixed number of decimal digits, but it operates on the binary64 floating-point representation of the number. Because decimal fractions like 1.005 cannot be exactly represented in binary \(it is stored as 1.004999999...\), toFixed rounds it down to '1.00' instead of up to '1.01'. This 'off-by-one-cent' bug appears sporadically in financial applications \(e.g., tax calculations\), seems non-deterministic to developers unfamiliar with IEEE 754, and is difficult to reproduce because it depends on the specific bit pattern of the input. The ECMAScript specification explicitly delegates the rounding to the abstract operation that acts on the mathematical value of the number, which inherits this binary imprecision. Alternatives like integer cents representation completely avoid these representation errors.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T01:52:42.711191+00:00— report_created — created