Floating-point numbers and money
A JS number is a 64-bit double (IEEE 754), so 0.1 + 0.2 gives 0.30000000000000004 and exact equality on fractions breaks. Money is stored as integers in minor units (cents) with the currency's number of decimals in mind: JPY has 0, KWD has 3. Percentages and rates need an explicit rounding rule from the specification, and toFixed rounds the binary value and returns a string.
TypeScript · JS traps
A sum comparison in a test fails on a difference in the 17th decimal place. How to count money in JS?
A test checks a cart total: two items, 0.1 and 0.2, must give 0.3. The check expect(total).toBe(0.3) fails with «Received: 0.30000000000000004». The bug is neither in the application nor in the test but in how JS stores fractional numbers. Someone who does not know this either «cures» the test with rounding in a random place or hides a real rounding defect in the product. This lesson explains where the error comes from, how to store and compare money and what to do with percentages and rates.
How it works and why. A JS number is a 64-bit floating-point number (IEEE 754, double): 52 bits for the significant part (53 bits of precision with the implicit bit), 11 for the exponent and 1 for the sign. The number is stored in binary and a fraction such as 0.1 has no finite binary form, just as 1/3 has none in decimal. So the nearest representable value is stored: in fact 0.1 is about 0.1000000000000000055. The error is small but it does not disappear on addition, it accumulates, and comparison for exact equality breaks. Integers within Number.MAX_SAFE_INTEGER (253 - 1, that is 9007199254740991) are represented exactly, and that is the basis of the approach to money.
0.1 + 0.2; // 0.30000000000000004
0.1 + 0.2 === 0.3; // false
(0.1).toFixed(20); // '0.10000000000000000555'
(0.3).toFixed(20); // '0.29999999999999998890'
1.005 * 100; // 100.49999999999999
(1.005).toFixed(2); // '1.00', not 1.01
Math.round(1.005 * 100); // 100, not 101
Note toFixed: it rounds the exact binary value and not the decimal one you see in the code. So (1.005).toFixed(2) gives '1.00' because the actual value is 1.00499999999999989. Besides, toFixed returns a string, not a number.
Two ways to store an amount
100.5 as a fraction
Addition, multiplying by a rate and comparison accumulate error. toBe fails and toBeCloseTo only hides the question of which rounding rule the product uses.
10050 minor units as an integer
Addition and subtraction are exact, comparison through toBe. Fractional arithmetic (percentages, rates) goes to one place with an explicit rounding rule.
Example: from fractions to minor units. Rules for working with money in tests:
- Store amounts in minor units (kopiykas, cents) as integers:
10050instead of100.50. - Know the number of minor units of the currency. Most have 2 but JPY has 0 and KWD has 3 (
Intlreports this throughresolvedOptions().maximumFractionDigits). Multiplying by a fixed 100 for every currency is a mistake. - Convert the string from an API response to minor units without an intermediate fractional
number:Math.round(Number('1.005') * 100)gives 100, not 101.
function toMinor(amount: string, digits = 2): number {
const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(amount);
if (!m) throw new Error('Bad amount: ' + amount);
const frac = m[3] ?? '';
if (frac.length > digits) {
throw new Error('Too many decimals: ' + amount); // no silent rounding
}
return Number((m[1] ?? '') + (m[2] ?? '') + frac.padEnd(digits, '0'));
}
toMinor('100.50'); // 10050
toMinor('-0.5'); // -50
The function works with a string and refuses extra decimal digits instead of silently rounding: a format mismatch must be visible.
Percentages, rates and the rounding rule. Fractional arithmetic still happens: a 1% fee, a conversion by a rate. Here you must know the rule from the specification because the options give different cents. Banks often apply banker's rounding (half-even): exactly in the middle it rounds to the even number. For 100.5 that is 100, while Math.round gives 101. Also Math.round rounds «up» for negatives: Math.round(-2.5) is -2.
// a 1% fee on 100.50 in minor units: 100.5, exactly in the middle
const fee = (10050 * 100) / 10000;
Math.round(fee); // 101 (half up)
roundHalfEven(fee); // 100 (banker's rounding)
function roundHalfEven(x: number): number {
const f = Math.floor(x);
const diff = x - f;
if (diff < 0.5) return f;
if (diff > 0.5) return f + 1;
return f % 2 === 0 ? f : f + 1;
}
For more complex calculations a decimal library (decimal.js, big.js) with an explicit rounding mode is used. What matters is that the expected result in a test comes from the specification and not from the output of the program itself.
// in minor units: integers, exact comparison
expect(toMinor('0.10') + toMinor('0.20')).toBe(toMinor('0.30'));
// fractional: only with a tolerance
expect(0.1 + 0.2).toBeCloseTo(0.3, 5);
// display: Intl, not string concatenation
const fmt = new Intl.NumberFormat('uk-UA', { style: 'currency', currency: 'UAH' });
fmt.format(1250.5); // '1\u00a0250,50\u00a0₴' (non-breaking spaces)
Limits and alternatives. toBeCloseTo(x, 5) compares with a tolerance of 5 digits and suits fractional quantities that are truly approximate (measurements, load percentages) but not money: there a difference of one cent is a bug. BigInt is needed for integers above 2^53 - 1, for example identifiers or amounts in the smallest units of cryptocurrencies. It does not mix with number in arithmetic and does not serialise to JSON:
10n + 1; // TypeError: Cannot mix BigInt and other types, ...
JSON.stringify({ id: 10n }); // TypeError: Do not know how to serialize a BigInt
Common mistakes.
toBefor fractional sums: the test depends on the order of operations.toFixed(2)as «rounding money»: it works on the binary value and returns a string.- Fixed multiplication by 100 for any currency: JPY and KWD give an error of 100 times or 10.
- Computing the expected value with the same code as the application: the rounding error repeats in both places and the test does not see it.
- Mixing
BigIntandnumberin one expression: TypeError.
Check yourself
The specification says a 1% fee on the amount with half-even rounding. For 10050 minor units the application returns 101 and the test expects 100. Who is right and what to check first?
Answer
100.5 lies exactly in the middle, so half-even gives the even 100 and half-up gives 101. If the specification says half-even the application has a defect (Math.round was used). First check what exactly the specification says and only then decide where the bug is.
Why does Math.round(Number('1.005') * 100) give 100 although «1.005» is 100.5 minor units, and how to get an exact result?
Answer
The number 1.005 in binary is slightly less than 1.005, the product with 100 is 100.49999999999999 and rounding goes down. The exact way: work with the string (split into integer and fractional parts) or use a decimal library, and either reject extra digits or round them by an explicit rule.
0.1 + 0.2 in JS does not equal 0.3 because of the binary representation of fractions. So I store and compare money as integers in minor units and not as fractions. Middle/Senior: I know that toFixed rounds the binary value and returns a string, that the number of minor units depends on the currency (JPY 0, KWD 3) and that fees and rates must be computed with an explicit rounding rule from the specification (half-even or half-up) through a decimal library. I derive the expected value in a test from the specification and not from the application code.