跪拜 Guibai
← All articles
JavaScript · Frontend · Algorithm

Money Is a Data-Model Problem, Not a Precision Problem: Store It as Integer Cents

By htzyl206 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Front-end money math that relies on `Number` is shipping off-by-one-cent bugs into every e-commerce checkout and wallet; the fix is free — integer minor units plus string parsing — and removes an entire class of reconciliation failures. Treating amounts as a data-model decision rather than a rounding footnote is the difference between a checkout that agrees with the backend and one that doesn't.

Summary

Floating-point math corrupts money in the front end on the seventeenth digit, and the failures aren't academic: `toFixed` rounds the binary value, not the literal, so `(1.005).toFixed(2)` yields 1.00; `parseInt(19.99 * 100)` truncates to 1998 cents; and `Math.round(price * 100)` is wrong for 1.005 and 8.575 while coincidentally right for 19.99. Accumulations drift by the third item, and splitting 19.99 among three people leaves the total short by a cent. The consequence: front end and backend reconcile differently on the same order.

The fix is to stop moving amounts as `Number`. Store integer minor units (cents, fils, or 10^exponent), parse from strings, and only convert to a decimal string at display time. The article quantifies three preconditions few teams respect: minor-unit exponents vary per ISO 4217 currency, the conversion to display must go through integer division and string concatenation rather than `/100`, and `Number.MAX_SAFE_INTEGER` caps the unit count — accumulation silently overflows past 2^53. BigInt is exact and unlimited but won't serialize to JSON, can't mix with Number, and its division truncates. The decimal.js library cleans up only when you feed it strings; passing `0.07 * 100` carries the double error straight into `Decimal`.

The strongest practical discovery is that `Intl.NumberFormat` rounds from the shortest decimal representation, not the binary truth, so it agrees with a hand-written halfExpand on `"1.005"` where `toFixed` doesn't. Since 2026 it accepts a decimal string directly, making formatting lossless for 19-digit amounts. But it has its own traps: `minimumFractionDigits` without `maximumFractionDigits` defaults the max to 3, rounding mode defaults to halfExpand which moves negatives away from zero (bad for refunds), and the currency digit count comes from CLDR not ISO 4217 — IQD is wrong. The call-to-action: store integer cents, parse from strings, format with `Intl` from that string, and never trust `Number` arithmetic inside the money path.

Takeaways
— `toFixed` rounds the binary value of a double, not the literal you wrote, so `(1.005).toFixed(2)` is "1.00", not "1.01".
— `parseInt(price * 100)` truncates toward zero, so `19.99 * 100` becomes 1998 cents instead of 1999.
— `Math.round(price * 100)` is wrong for `1.005` and `8.575` while coincidentally right for `19.99`; the error is unpredictable at code level.
— Accumulating 0.1 ten thousand times yields 1000.0000000001588, and the error appears as early as the third addition.
— Splitting 19.99 across three people with `each.toFixed(2)` sums to 19.98; the correct approach is integer floor division plus distributing the remainder.
— `Intl.NumberFormat` rounds from the shortest decimal representation, while `toFixed` rounds from the binary value, so they produce different results for values like 1.005, 2.675, and 8.575.
— Since 2026, `Intl.NumberFormat` accepts a decimal string directly and formats 19-digit amounts without loss; older browsers silently ignore `roundingMode` options.
— The default `roundingMode` `halfExpand` moves negative amounts away from zero, so refunds using the default will refund less.
— Omitting `maximumFractionDigits` when setting `minimumFractionDigits` defaults the max to 3, producing unintended fractional digits.
— `Intl`'s currency digit count comes from CLDR, not ISO 4217; IQD is a mismatch (3 in ISO, 0 in Intl).
— `decimal.js` is only exact when its input is a decimal string; `new Decimal(0.07 * 100)` carries the double error through.
— Integer cents in `Number` are about 73x faster than `decimal.js` for a million additions (2.8 ms vs 208.4 ms).
Conclusions

The real instability isn't `0.1 + 0.2`; it's `toFixed` and `Intl` rounding off the same double differently because they round different representations, so a frontend that formats one way and a backend that formats another will disagree on the same value.

Storing money as integer cents only works if you accept three hidden preconditions: currency-specific minor-unit exponents, no floating-point conversions at the display boundary, and a capacity check for the safe-integer ceiling. Most teams implement the first and forget the last two.

`Intl` accepting a decimal string is the quiet game-changer here: it turns formatting into an exact string operation, so the display layer can stop depending on any `Number` math. The catch is that it does no validation, so an empty string becomes "0.00" and commas are rejected.

BigInt gives arbitrary precision but forces a serialization contract and explicit division rounding; the `==` vs `===` comparison trap is a classic hidden bug.

The decimal.js performance gap (73x) is exactly why integer cents are recommended for hot paths and decimal libraries are reserved for complex multi-currency logic.

The mismatch between ISO 4217 and CLDR (IQD) warns that any currency-exponent table needs to be maintained by the developer, not inferred from `Intl`.

Concepts & terms
Shortest decimal representation
ECMAScript's algorithm for converting a Number to a string picks the fewest characters that uniquely round-trip to the same double. `Intl` rounds based on this string, while `toFixed` rounds the full binary value, so they can differ at the 5 digit.
ISO 4217 minor unit exponent
The number of fractional digits a currency legally defines, e.g., USD=2, JPY=0, KWD=3. Storing money as integer cents means using 10^exponent as the unit, not a hardcoded 100.
Banker's rounding (halfEven)
A tie-breaking rule where values exactly at the midpoint round to the nearest even digit; it reduces systematic bias over many roundings but flips the direction of negative amounts compared to half-up.
CLDR data
Unicode's Common Locale Data Repository that determines `Intl.NumberFormat`'s currency digit counts. It occasionally diverges from ISO 4217, as with IQD, so storage and display digit counts should be maintained separately.
From the discussion
Featured comments
组合搭配函数

0.1+0.2, anyone who's stepped in this pit knows. Reconciliation being off by a cent can eat up an entire afternoon. Storing integer cents and formatting at the display layer—that's the proper way.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗