Money Is a Data-Model Problem, Not a Precision Problem: Store It as Integer Cents
Money Math: Why the Frontend Should Never Store Money as a Float
If you've written a shopping cart, a coupon, a split, or a red packet, you've likely written this line:
const total = items.reduce((a, b) => a + b.price, 0);
Then at the end of some month you discover that the frontend's 100.00 yuan is the backend's 99.99 yuan. Neither side is wrong, neither side throws an error; it's just that from the 17th decimal place onward the two diverge.
This is not a "precision problem" — it's a data-model problem. This article, tested on Node 22/24/26 and a real Chrome 152, quantifies exactly how storing money as a float can go wrong, then gives four workable paths — and the failure boundary of each.
The core conclusion is one sentence: Money must not flow through the system as a Number; it must be an integer of the smallest unit, only becoming a decimal string at the moment of display.
1. Quantifying how "storing money as a float" fails
Most online discussions of floating-point error stop at 0.1 + 0.2 !== 0.3. But the things that actually keep you at work late are the five concrete scenarios below.
1.1 toFixed rounds the binary truth, not the literal you wrote
This is the most counterintuitive one. (1.005).toFixed(2) returns "1.00", not the "1.01" you expected.
(1.005).toFixed(2); // "1.00"
(2.675).toFixed(2); // "2.67"
(8.575).toFixed(2); // "8.57"
(0.615).toFixed(2); // "0.61"
Why? Because toFixed rounds the binary value of this double, and that value is a tiny bit smaller than the literal:
| Literal | Binary value of the double (21 significant digits) | toFixed(2) |
|---|---|---|
1.005 |
1.00499999999999989342 |
"1.00" |
2.675 |
2.67499999999999982236 |
"2.67" |
8.575 |
8.57499999999999928946 |
"8.57" |
0.615 |
0.614999999999999991118 |
"0.61" |
As a side note, even 0.1 itself is imprecise:
(0.1).toPrecision(21); // "0.100000000000000005551"
0.1's real value is 0.1000000000000000055511151231257827..., slightly larger than 0.1. Everything you think of as a "decimal fraction" is, at runtime, a binary approximation.
Criterion: toFixed is not "round to two decimal places"; it's "truncate the binary value of that double to two decimal places." These two things part ways at the 5 digit.
To be clear: this is not a bug in
toFixed. The ECMAScript spec requirestoFixedto round based on "the mathematical value of this Number," and the mathematical value of1.005is1.00499999999999989342.... Your1.005is just the decimal spelling in source code; at runtime it is no longer that number.
1.2 Math.round and parseInt give different answers on the same number
The step from "yuan" to "cents" is the most common line in money code:
const cents = Math.round(price * 100);
But someone else writes:
const cents = parseInt(price * 100);
These two diverge on 19.99:
| Original | × 100 double value |
Math.round |
parseInt |
Correct |
|---|---|---|---|---|
19.99 |
1998.9999999999998 |
1999 | 1998 | 1999 |
2.675 |
267.5 |
268 | 267 | 268 |
0.615 |
61.5 |
62 | 61 | 62 |
1.15 |
114.99999999999999 |
115 | 114 | 115 |
8.575 |
857.4999999999999 |
857 | 857 | 858 |
parseInt is a cent short here. The reason: parseInt truncates toward zero, Math.round rounds half up — and 19.99 * 100 comes out as 1998.9999999999998, which truncates to 1998.
Criterion: never use parseInt/parseFloat on the result of × 100 in money scenarios. But more importantly: that whole line shouldn't exist, as the next section explains.
1.3 The "yuan → cents" step has a higher error rate than you think
I ran a batch of common prices:
1.005 * 100 = 100.49999999999999 Math.round → 100 (expected 101)
8.575 * 100 = 857.4999999999999 Math.round → 857 (expected 858)
19.99 * 100 = 1998.9999999999998 Math.round → 1999 (accidentally correct)
0.29 * 100 = 28.999999999999996 Math.round → 29 (accidentally correct)
Criterion: Math.round(price * 100) is not 100% correct, and you can't predict it at the code level. It's accidentally right for 19.99 and 0.29, and wrong for 1.005 and 8.575. The only reliable approach is to never go through double — parse directly from the string.
// Parse a string directly into cents, never touching a double
function toCents(str) {
const m = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(str.trim());
if (!m) throw new Error(`Invalid amount: ${str}`);
const sign = m[1] === '-' ? -1 : 1;
const yuan = Number(m[2]);
const frac = (m[3] ?? '').padEnd(2, '0');
return sign * (yuan * 100 + Number(frac));
}
1.4 Accumulation error: 10,000 items of 0.1 yuan
A single 0.1 is fine; accumulating it is a problem:
let sum = 0;
for (let i = 0; i < 10000; i++) sum += 0.1;
// sum = 1000.0000000001588
// expected 1000, error 1.588e-10
I recomputed this loop with exact rational arithmetic using BigInt and found the first deviation from the mathematically true value:
| Count | double accumulation | exact rational accumulation |
|---|---|---|
| 3rd | 0.30000000000000004 |
0.3000000000000000166533453 |
| 10000th | 1000.0000000001588 |
1000.0000000000000555111512312 |
Criterion: floating-point accumulation error is "each item is off by a tiny bit," not "the last step is off." And it deviates as early as the third item — testing with 3 items will never reveal the problem.
1.5 Splitting: one more person, one cent less
Split 19.99 among 3 people:
const each = 19.99 / 3; // 6.663333333333333
const rounded = Number(each.toFixed(2)); // 6.66
// 3 × 6.66 = 19.98, off by 0.01
Split 19.99 among 7 is worse:
const each = 19.99 / 7; // 2.8557142857142854
const rounded = Number(each.toFixed(2)); // 2.86
// 7 × 2.86 = 20.02, over by 0.03
This is a "totals don't add up" problem, not a "precision" problem. Even if you replace floats with any precision, as long as you do "divide first, round later", the total never matches.
Criterion: splitting must use "divide integer first, then distribute the remainder to the first few people", any "divide then round" approach breaks total conservation.
function splitCents(totalCents, n) {
const base = Math.floor(totalCents / n);
const rest = totalCents % n;
return Array.from({ length: n }, (_, i) => base + (i < rest ? 1 : 0));
}
splitCents(10000, 3); // [3334, 3333, 3333] sum 10000
splitCents(100, 6); // [17, 17, 17, 17, 16, 16] sum 100
2. Integer cents: the safest path and its three hidden preconditions
Storing amounts as integer cents throughout is the standard answer for money math. It eliminates all five problems above:
const totalCents = items.reduce((a, b) => a + b.priceCents, 0);
// All-integer arithmetic, no error, no accumulation
But the phrase "integer cents" hides three preconditions; missing any one breaks it.
2.1 Precondition 1: The "cent" of different currencies is not the same thing
ISO 4217 specifies the minor unit exponent for each currency. Measured with Intl.NumberFormat:
| Digits | Currencies (partial) |
|---|---|
| 0 | JPY KRW VND CLP ISK XAF XOF XPF UGX PYG RWF GNF KMF DJF VUV IQD MGA |
| 2 | USD CNY EUR GBP HKD SGD AUD CAD CHF NZD |
| 3 | KWD BHD OMR JOD TND LYD |
| 4 | CLF UYW |
If your system only deals with RMB and USD, cents is 100; but touch JPY or the Kuwaiti dinar and the unit itself changes.
// 1999 cents for JPY is ¥1,999, not ¥19.99
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'JPY' }).format(1999);
// "¥1,999"
// 12.5 KWD is 12,500 thousandths, not 1,250
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'KWD' }).format(12.5);
// "KWD 12.500"
Criterion: the "cent" of integer cents is not a constant; it is 10 ** ISO4217[currency].exponent. Any code hardcoding /100 is wrong for currencies with non-2 digits.
2.2 Precondition 2: Intl receives the main unit amount, not cents
This is the easiest trap to step into. The currency option of Intl.NumberFormat expects yuan/main unit:
const nf = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
nf.format(1999); // "$1,999.00" ← this is 1999 yuan, not 1999 cents
nf.format(19.99); // "$19.99"
So to go from cents to display, you must first convert to main unit. And if you do it with /100, you're back in float:
// Dangerous: convert to double first, then format
nf.format(Number(1999) / 100); // "$19.99" ← works here, but the value went through double
// Safe: integer cents to decimal string, never touching double
const cents = 1999n;
const str = (cents / 100n).toString() + '.' + (cents % 100n).toString().padStart(2, '0');
nf.format(str); // "$19.99" ← the value never became a double
Criterion: integer cents to display should be a path of "integer division + modulo + string concatenation", not /100. The test is simple: if any intermediate value in the conversion chain is a Number, precision is half-broken.
2.3 Precondition 3: Number can't hold the ceiling of integer cents
Number.MAX_SAFE_INTEGER is 9007199254740991. Storing cents at that ceiling:
Number.MAX_SAFE_INTEGER / 100;
// 90071992547409.91 yuan ≈ 90 trillion yuan
Sounds enough, but at the "cent" unit, some currencies have a much lower threshold. Three-decimal currencies (KWD/BHD/OMR/JOD/TND/IQD/LYD) use thousandths, so the same safe-integer ceiling only covers 9 billion yuan.
Beyond that, Number simply can't hold it:
Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER; // false (here, just 1 short)
9007199254740993n to Number = 9007199254740992 // mantissa flattened
Criterion: Number storing cents has a ceiling of MAX_SAFE_INTEGER minor units. A single amount far below the limit doesn't mean safe — the limit is reached after accumulation, and overflow happens silently without any exception.
// Typical silent overflow
let total = 0;
for (const item of items) total += item.priceCents; // loses cents past 2^53
3. BigInt for money: precise, but three boundaries to handle
BigInt has been around since ES2020 and is natural for money:
const total = 1999n + 2899n + 1005n; // 5893n
But its boundaries are completely different from Number, and there are three pitfalls.
3.1 Pitfall 1: BigInt and Number cannot mix, and silent comparison is dangerous
1n + 1;
// TypeError: Cannot mix BigInt and other types, use explicit conversions
Addition throws, which is good. But comparison does not throw:
1999n === 1999; // false
1999n == 1999; // true ← loose equality treats them as the same
1999n == 1999 returns true, but 1999n === 1999 returns false. In old code that compares amounts with ==, this directly plants a landmine.
3.2 Pitfall 2: BigInt can't go into JSON
JSON.stringify({ amount: 1999n });
// TypeError: Do not know how to serialize a BigInt
And BigInt.prototype.toFixed doesn't exist:
(1999n).toFixed(2);
// TypeError: bc[0].toFixed is not a function
Criterion: the external contract for BigInt amounts can only be "string" or "two fields (main unit + minor unit)". When serialization is needed, convert explicitly:
JSON.stringify({ amount: 1999n.toString() }); // '{"amount":"1999"}'
JSON.stringify({ amount: Number(1999n) }); // '{"amount":1999}' ← back in Number land
The second form invites the precision problem back. If the amount can exceed the safe integer, only the string works.
3.3 Pitfall 3: BigInt division truncates, not rounds
5893n / 100n; // 58n ← discards 93 cents
5893n / 100n; // 58n, not 59n
BigInt's / always truncates toward zero. If you were thinking "round to the nearest yuan", BigInt won't do it for you.
Criterion: when using BigInt for money, division must be explicitly written as "add half then divide" or "take quotient and remainder, then decide to carry", not rely on /'s default.
function bigintRoundDiv(a, b) { // round-half-up division
const q = a / b, r = a % b;
return r * 2n >= b ? q + (a < 0n ? -1n : 1n) : q;
}
bigintRoundDiv(5893n, 100n); // 59n
3.4 BigInt's upside: no upper bound, and comparisons are naturally correct
2n ** 100n; // 1267650600228229401496703205376n
BigInt has arbitrary precision, no MAX_SAFE_INTEGER ceiling. And "comparing magnitude" is the most frequent operation in money scenarios, where BigInt wins outright:
1999n > 1998; // true ← no `==` trap
Criterion: if your amount can exceed Number.MAX_SAFE_INTEGER minor units, or you need many exact comparisons between amounts, BigInt is the only correct choice. The cost: no JSON, no mixing with Number, division doesn't round half up — all three must be isolated at the type level.
4. Intl.NumberFormat: more precise than you think, but its precision comes from a counterintuitive source
This is the most important section of the article. Many people think "just use Intl.NumberFormat and you're fine" — the conclusion is right, but the reason is different from what most assume.
4.1 Key finding: Intl and toFixed give different answers for the same number
const p2 = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
p2.format(1.005); // "1.01"
(1.005).toFixed(2); // "1.00" ← different!
p2.format(2.675); // "2.68"
(2.675).toFixed(2); // "2.67" ← different!
p2.format(8.575); // "8.58"
(8.575).toFixed(2); // "8.57" ← different!
Same double, two rounding results. So what does Intl actually round?
The answer: Intl rounds the "shortest decimal representation" of the double, while toFixed rounds its binary value.
Number's ToString algorithm (ECMAScript 6.1.6.1.20) specifies that a double is converted to the shortest decimal string that uniquely round-trips to itself. So:
String(1.005); // "1.005" ← shortest representation
(1.005).toPrecision(21); // "1.00499999999999989342" ← binary truth
Intl uses the former ("1.005") for halfExpand → 1.01; toFixed uses the latter (1.00499999...) → 1.00.
I hand-implemented a halfExpand on the shortest decimal representation, and the results match Intl exactly:
function halfExpandDecimal(str, digits) {
const neg = str.startsWith('-');
const s = neg ? str.slice(1) : str;
const [ipRaw, fpRaw = ''] = s.split('.');
const ip = ipRaw.replace(/^0+(?=\d)/, '');
if (fpRaw.length <= digits) return (neg ? '-' : '') + ip + '.' + fpRaw.padEnd(digits, '0');
const keep = fpRaw.slice(0, digits);
let val = BigInt(ip + keep);
if (fpRaw[digits] >= '5') val += 1n;
const rs = val.toString().padStart(ip.length + digits, '0');
return (neg ? '-' : '') + rs.slice(0, rs.length - digits) + '.' + rs.slice(rs.length - digits);
}
Running it against Intl across 18 cases (positive/negative, integer carry, thousands separator, tiny numbers) yields byte-for-byte identical strings:
| Value | toFixed(2) |
Hand (shortest decimal) | Intl |
|---|---|---|---|
1.005 |
1.00 |
1.01 |
1.01 |
2.675 |
2.67 |
2.68 |
2.68 |
8.575 |
8.57 |
8.58 |
8.58 |
0.615 |
0.61 |
0.62 |
0.62 |
0.005 |
0.01 |
0.01 |
0.01 |
-2.675 |
-2.67 |
-2.68 |
-2.68 |
Note the 0.005 row: toFixed gives 0.01 and Intl also gives 0.01 — because 0.005's double value is 0.005000000000000000104..., greater than 0.005, so both round up. The same toFixed and Intl agree on this row and disagree on the 1.005 row, which precisely proves they round on different bases, not that "Intl is just toFixed with a thousands separator."
Criterion 1: toFixed rounds "what this double actually is", Intl rounds "how you originally wrote this number". The former is the "physical value", the latter is the "text value" — for money, the text value is what the user inputs.
Criterion 2 (the most practical in this article): Intl's rounding equals "first String(x), then round that decimal string half-up." So if the amount originates from a user string, take the string path from the start; don't Number() it first and then format.
4.2 A stronger weapon: Intl accepts strings directly
Since ECMA-402 v3, Intl.NumberFormat.prototype.format can take a decimal string, parsed exactly as a decimal literal, never passing through a double:
const nf = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
nf.format('987654321987654321');
// "$987,654,321,987,654,321.00" ← 19 digits, none lost
nf.format(987654321987654321);
// "$987,654,321,987,654,300.00" ← Number path, mantissa flattened to 300
This is the second criterion that most people can't write. In large-amount scenarios (e.g., cent-stored back-office reconciliation amounts, IDs over 19 digits), the string path is the only lossless one.
I tested the syntax boundary of string input:
| Input | Intl output |
Notes |
|---|---|---|
"19.99" |
"19.99" |
Normal |
"1e3" |
"1,000.00" |
Supports scientific notation |
"0x10" |
"16.00" |
Supports hex literals |
"1.5e2" |
"150.00" |
Normal |
".5" |
"0.50" |
Normal |
" 12.5 " |
"12.50" |
Leading/trailing whitespace tolerated |
"1,999" |
"NaN" |
Thousands comma not accepted |
"1_000" |
"NaN" |
Underscore not accepted |
"abc" |
"NaN" |
Invalid input doesn't throw, returns NaN |
"" |
"0.00" |
Empty string becomes 0 |
Criterion 3: Intl's string path is "decimal literal parsing", not "string-to-number then format". Accepting 0x10 shows it follows the StringNumericLiteral grammar; turning "" into 0 shows it does not do input validation — you must handle empty and invalid strings yourself.
4.3 Browser support: the string path is Baseline high
From web-features (verified 2026-11-24):
| Capability | Baseline | Chrome | Edge | Firefox | Safari | Safari iOS |
|---|---|---|---|---|---|---|
Intl.NumberFormat itself |
high (2020-03-28) | 24 | 12 | 29 | 10 | 10 |
format accepts decimal string |
high (2026-02-01) | 106 | 106 | 116 | 15.4 | 15.4 |
options.roundingMode |
high (2026-02-01) | 106 | 106 | 116 | 15.4 | 15.4 |
options.roundingIncrement |
high (2026-02-01) | 106 | 106 | 116 | 15.4 | 15.4 |
options.trailingZeroDisplay |
high (2026-02-01) | 106 | 106 | 116 | 15.4 | 15.4 |
options.roundingPriority |
high (2026-02-01) | 106 | 106 | 116 | 15.4 | 15.4 |
Criterion 4: the string path is in the Baseline high range (available in all browsers from Feb 2026), but roundingMode and the other options arrived in the same batch — if you need to explicitly set a rounding mode, the floor is Chrome 106 / Firefox 116 / Safari 15.4 (Aug 2023). Older browsers silently ignore unknown options and run with default halfExpand, without throwing.
4.4 Nine rounding modes, and direction reversal on negatives
roundingMode has nine values. This is the measured comparison (Chrome 152 and Node 22/24/26 all produce identical output):
| Mode | 2.235 |
2.245 |
2.255 |
-2.235 |
-2.245 |
-2.255 |
|---|---|---|---|---|---|---|
ceil |
2.24 | 2.25 | 2.26 | -2.23 | -2.24 | -2.25 |
floor |
2.23 | 2.24 | 2.25 | -2.24 | -2.25 | -2.26 |
expand |
2.24 | 2.25 | 2.26 | -2.24 | -2.25 | -2.26 |
trunc |
2.23 | 2.24 | 2.25 | -2.23 | -2.24 | -2.25 |
halfCeil |
2.24 | 2.25 | 2.26 | -2.23 | -2.24 | -2.25 |
halfFloor |
2.23 | 2.24 | 2.25 | -2.24 | -2.25 | -2.26 |
halfExpand (default) |
2.24 | 2.25 | 2.26 | -2.24 | -2.25 | -2.26 |
halfTrunc |
2.23 | 2.24 | 2.25 | -2.23 | -2.24 | -2.25 |
halfEven |
2.24 | 2.24 | 2.26 | -2.24 | -2.24 | -2.26 |
Two things worth remembering:
First, ceil on a negative number means "toward +∞", i.e., the absolute value gets smaller. -2.235 under ceil becomes -2.23, not -2.24. Many people get this backwards — ceil's name means "toward positive infinity", which for negatives is "less negative".
Second, the default halfExpand on negatives is "away from zero", matching the positive "round half up" intuition: -2.245 → -2.25. But halfEven (banker's rounding) makes -2.245 → -2.24.
Criterion 5: the rounding direction for money must be written explicitly, not left to defaults. Because the default halfExpand moves negatives away from zero — refunds (negative amounts) using the default will refund less, and that's the direction business cares about most.
Accounting systems conventionally use
halfEven(banker's rounding), which eliminateshalfExpand's systematic bias over millions of roundings. But note whetherhalfEven's bias direction matches your business — refund scenarios might actually be the opposite.
4.5 An easy-to-miss interaction
Writing only minimumFractionDigits without maximumFractionDigits defaults the latter to 3:
new Intl.NumberFormat('en-US', { minimumFractionDigits: 2 }).resolvedOptions().maximumFractionDigits;
// 3 ← not 2
new Intl.NumberFormat('en-US', { minimumFractionDigits: 2 }).format(4.33145);
// "4.331" ← three decimals!
Criterion 6: money formatting must set both minimumFractionDigits and maximumFractionDigits. Omitting one doesn't "reduce precision" — it adds two decimal places you never asked for.
4.6 Intl's currency digits don't always match ISO 4217
This is a trap I dug out during testing that almost nobody writes about.
I compared the Intl-parsed digit counts of 32 common currencies against the authoritative ISO 4217 table:
| Currency | ISO 4217 digits | Intl parsed digits |
|---|---|---|
| USD / CNY / EUR / GBP etc. | 2 | 2 |
| JPY / KRW / VND / CLP etc. | 0 | 0 |
| KWD / BHD / OMR / JOD / TND / LYD | 3 | 3 |
| IQD | 3 | 0 ← mismatched |
31/32 match; the only mismatch is IQD (Iraqi dinar).
The reason: Intl's currency digits come from CLDR data, not ISO 4217. CLDR reflects "how many digits this currency is usually written with in everyday use", while ISO 4217 defines "the unit definition of the currency". There's a tc39/ecma402 issue #134 discussing exactly this — even MDN's claim that "default fractional digits come from ISO 4217" doesn't fully hold in Chrome.
Criterion 7: maintain your own table of minor-unit digit counts; don't infer from Intl. Because:
Intlgives CLDR values, which differ from ISO 4217 (IQD is the example);- display digits ≠ storage digits. An IQD amount stored with three digits (
12.345) can be displayed as an integer — storage must follow ISO 4217, display can follow business convention.
// Storage uses ISO exponent, display follows CLDR/business
const ISO_EXPONENT = { USD: 2, JPY: 0, KWD: 3, IQD: 3, CLF: 4, ... };
4.7 Intl can take BigInt directly
const nf = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
nf.format(1999n); // "$1,999.00"
BigInt can go straight into Intl without converting to Number. This is handy in the "BigInt integer cents + direct display" scenario.
But BigInt has no fractional digits: nf.format(1999n) is 1999 yuan, not 1999 cents. So a BigInt amount still needs the "cents → main unit" conversion before being displayed as currency.
5. Decimal library: full-featured, but one necessary trap
decimal.js is the most common decimal library. Tested version: decimal.js 10.x (npm i decimal.js).
5.1 Basic ability
const { Decimal } = require('decimal.js');
Decimal.set({ precision: 20, rounding: Decimal.ROUND_HALF_EVEN });
new Decimal('0.1').plus(new Decimal('0.2')).toString(); // "0.3"
new Decimal('2.675').toFixed(2); // "2.68"
new Decimal('100').dividedBy(3).toFixed(2); // "33.33"
It ships with 8 rounding modes, measured:
| Mode | 1.005 |
2.675 |
1.015 |
-1.005 |
0.125 |
|---|---|---|---|---|---|
ROUND_DOWN |
1.00 | 2.67 | 1.01 | -1.00 | 0.12 |
ROUND_CEIL |
1.01 | 2.68 | 1.02 | -1.00 | 0.13 |
ROUND_FLOOR |
1.00 | 2.67 | 1.01 | -1.01 | 0.12 |
ROUND_HALF_UP |
1.01 | 2.68 | 1.02 | -1.01 | 0.13 |
ROUND_HALF_DOWN |
1.00 | 2.67 | 1.01 | -1.00 | 0.12 |
ROUND_HALF_EVEN (default) |
1.00 | 2.68 | 1.02 | -1.00 | 0.12 |
ROUND_HALF_CEIL |
1.01 | 2.68 | 1.02 | -1.00 | 0.13 |
ROUND_HALF_FLOOR |
1.00 | 2.67 | 1.01 | -1.01 | 0.12 |
Note that ROUND_HALF_EVEN and ROUND_HALF_UP give different results on 1.005 (1.00 vs 1.01) — because 1.005's exact decimal value is 1.005, exactly at the midpoint; halfEven rounds to the even 1.00, halfUp rounds to 1.01.
This also explains why Intl's default halfExpand (equivalent to halfUp) and decimal.js's default halfEven fight each other. In money scenarios, this difference is a real cent.
5.2 Trap: new Decimal(0.1) is not what you think
new Decimal(0.1).toString(); // "0.1"
new Decimal(0.1).minus(new Decimal('0.1')).toFixed(20); // "0.00000000000000000000"
It looks like Decimal has "washed away" the double's error. But it's not because Decimal is smarter — it's because for a number input it follows the String(n) path, re-parsing the double's shortest decimal representation.
This creates a very practical trap:
// You think you're using a decimal library
new Decimal(0.1).plus(0.2).toString(); // "0.3" ← accidentally correct
// The real trap: compute into a double first, then into Decimal
new Decimal(0.07 * 100).toString(); // "7.000000000000001" ← error already inside
new Decimal(0.07 * 100).toFixed(2); // "7.00" ← toFixed covers it back
// 1000 accumulations
let s = new Decimal(0);
for (let i = 0; i < 1000; i++) s = s.plus(0.1);
s.toFixed(20); // "100.00000000000000000000" ← note: also clean here
let d = 0; for (let i = 0; i < 1000; i++) d += 0.1;
d.toFixed(20); // "99.99999999999859312538" ← the native double's real error
Criterion 8: a decimal library is only truly exact when the input is a decimal string. Passing a number means it does a String(n) rescue — it catches short decimals like 0.1, but not composite expressions computed first and then passed in.
// Correct: source is a string
new Decimal('0.07').times(100).toString(); // "7"
// Wrong: computed in double first
new Decimal(0.07 * 100).toString(); // "7.000000000000001"
This criterion generalizes into an engineering rule: the "source" of an amount must be a string or integer; the moment any step turns it into a number, precision guarantees end at that step.
5.3 Performance: decimal library is two orders of magnitude slower than integer cents
Rough measurement of 1 million additions (Node 22, same machine):
| Approach | 1 million additions |
|---|---|
Integer cents (Number integer) |
2.8 ms |
Decimal |
208.4 ms |
About a 73x gap. That's not to say Decimal is unusable — a few microseconds per operation is fine for on-page money math. But it shows that for high-frequency scenarios like "summing tens of thousands of line items", Decimal is wasteful; for a checkout page that computes a few dozen orders once, the readability and correctness Decimal buys is worth it.
5.4 Decimal's JSON trap
JSON.stringify(new Decimal('19.99')); // '"19.99"' ← it's a string!
JSON.stringify({ amount: new Decimal('19.99') }); // '{"amount":"19.99"}'
Decimal's toJSON returns a string, not a number. If the backend receives it as number, it gets a string type, breaking the type contract.
Criterion 9: with Decimal, you must explicitly define the serialization contract (all strings, or all Number), and not let the default toJSON behavior leak into the API.
6. Comparison and selection of the four paths
Now line up the four paths:
| Approach | Precision | Serialization | Performance | Best for |
|---|---|---|---|---|
Float (Number) |
has error | natively compatible | fastest | never for money |
Integer cents (Number) |
exact (within safe integer) | natively compatible | very fast | single currency with 2 digits, amount within limit |
Integer cents (BigInt) |
exact, no limit | can't go into JSON | fast | large amounts, exact comparisons |
| Decimal library | exact (when input is string) | requires own contract | ~73x slower | multi-currency, complex splits, FX |
Intl string path |
exact at display | no requirement | fast | display layer of all scenarios |
6.1 Recommended layered approach
// 1) Source: parse string into integer cents, never through double
function parseAmount(input, exponent = 2) {
const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(String(input).trim());
if (!m) throw new TypeError(`Invalid amount: ${input}`);
const digits = (m[3] ?? '').slice(0, exponent).padEnd(exponent, '0');
const scale = 10 ** exponent;
return Number(m[2]) * scale + Number(digits) * (m[1] ? -1 : 1);
}
// 2) Middle: integer arithmetic throughout
const totalCents = items.reduce((a, b) => a + b.priceCents, 0);
// 3) Display: integer cents → decimal string → Intl
function formatCents(cents, currency, exponent = 2) {
const neg = cents < 0;
const abs = Math.abs(cents);
const scale = 10 ** exponent;
const text = `${Math.floor(abs / scale)}.${String(abs % scale).padStart(exponent, '0')}`;
return new Intl.NumberFormat('en-US', {
style: 'currency', currency,
minimumFractionDigits: exponent,
maximumFractionDigits: exponent,
}).format(neg ? `-${text}` : text);
}
formatCents(1999, 'USD'); // "$19.99"
Note step 3: integer cents are turned into a decimal string first, then handed to Intl. This both avoids the double of /100 and gets Intl's localization (sign position, thousands separator, currency name).
6.2 A criterion I almost wrote wrong
I initially wanted to write: "Intl.NumberFormat can correctly handle money, so using Intl is enough."
That's wrong. Intl only solves the display layer. It does not solve:
- the rounding after each accumulation step (
Intlrounds only once, at the final format); - the total conservation when splitting (
Intldoesn't care how you divide); - the storage precision (
Intlformatting still produces a string, andNumberaccumulation still produces a double).
The correct statement: "Intl is the correct answer for the display layer; it's even more accurate than toFixed (because it rounds on the decimal text); but it can't replace integer cents or a decimal library as the computation layer."
6.3 Where Math.sumPrecise fits here
ES2026's Math.sumPrecise solves "order independence of summation" — it guarantees this sum is correct, but doesn't guarantee later multiplications or divisions are correct.
Math.sumPrecise(items.map(i => i.priceCents)); // all integers, exact
Under the integer-cents approach, Math.sumPrecise's precision gain is zero (integer addition is already exact). But its "order independence" guarantee is still valuable: if your cart list order can change (user sorting, nondeterministic API order), and you need to reconcile against the backend, this guarantee is a must-have.
Criterion 10: in the integer-cents scheme, Math.sumPrecise is not a precision tool, it's a consistency tool. This is completely different from its role in scientific computing; don't mix them up.
7. Self-check checklist
After writing money code, check each item:
| Check item | Criterion |
|---|---|
| Where does the amount come from | Is it a string or a number? If it's a number, precision ends there |
| Storage unit | Is it an integer minor unit? Is the exponent 10 ** ISO4217[currency].exponent |
| Convert to cents/yuan | Is there a * 100 or / 100? If yes, there's risk |
| Truncation function | Is parseInt/parseFloat anywhere in the amount path? |
| Splitting | Is it "integer first, then remainder" or "divide then round"? |
| Accumulation | Is there overflow potential? Did you check Number.isSafeInteger? |
| BigInt | Does it go into JSON? Does it mix with Number? |
| Display | Do you use Intl or toFixed? Are both minimumFractionDigits and maximumFractionDigits set? |
| Rounding direction | Did you explicitly set roundingMode? Is the negative direction correct? |
| Currency digits | Do you use your own table or infer from Intl? |
Appendix: Test environment for this article
| Item | Value |
|---|---|
| Node | 22.22.2 / 24.22.3 / 26.13.1 (all three produce identical output) |
| Browser | Chrome 152.0.7977.75 (headless + local HTTP server, not file://) |
| ICU | process.versions.icu = 78.2 |
| Decimal library | decimal.js 10.x (npm i decimal.js) |
| Baseline data | web-features read 2026-11-24 |
| Exact recomputation | Self-implemented BigInt exact rational arithmetic (DataView to unpack double binary bits) |
All numerical conclusions are measured outputs from the above environment, not derived by inference.
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
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.