MONEY IN FLOATING POINT
A tenth has no exact binary form
Owoleaf adds a ₦0.10 fee to a JavaScript number a million times. It prints the total with toFixed(2), then checks it against the processor's invoice of ₦100,000 with ===. What do you see?
A double stores a number as a binary fraction. Halves and quarters are exact. A tenth is not: in binary it repeats for ever, as a third does in decimal. The double nearest 0.10 is a hair over it, the one nearest 8.29 a hair under, and every addition rounds again. A million ₦0.10 fees come to 100000.00000133288.
The fix is to stop asking binary to hold decimal fractions. Count integer kobo, or use a decimal type. Kahan summation is the float-side mitigation: it carries the bits each addition loses into the next one, and it does make this sum exact. It cannot repair a value that was never exact, or a comparison.
let total = 0;
for (const fee of fees) total += fee; // 0.1, a million times
if (total !== invoice) raise('recon mismatch'); // 100000.00000133288 !== 100000
const kobo = Math.trunc(8.29 * 100); // 828.9999999999999 -> 828
if (0.1 + 0.2 > 0.3) refuse(); // 0.30000000000000004// Integer kobo from the first moment the amount exists.
const kobo = parseKobo('8.29'); // 829, from the digits
let total = 0; // or BigInt for very large sums
for (const fee of feesKobo) total += fee; // 10, a million times = 10000000
if (total !== invoiceKobo) raise('recon mismatch');
// Decimal types (BigDecimal, Python decimal, SQL NUMERIC) are also exact
// for these sums. Kahan summation is not a substitute: it fixes only the sum. Watch the four checks. FLOAT LEDGER turns the total red after the first batch, fails the reconciliation, refunds ₦8.29 as 828 kobo and refuses ₦0.10 + ₦0.20 against a ₦0.30 cap. KAHAN SUMMATION turns the first two green and leaves the last two red. The ₦8.29 conversion never goes through the sum. The cap’s inputs were never exact: Kahan returns the double nearest 0.1 + 0.2 as stored, 0.30000000000000004, which is still above the double 0.3. INTEGER KOBO keeps all four green on the same million fees.
The ledger is integer kobo and every check is green. Then a partner sends a ₦8.29 refund as a JSON number, {"amount": 8.29}, and someone converts it at the edge. Inject one conversion that sends the wrong kobo.
GOAL: a refund sends the wrong number of kobo
Same float ledger, same million fees. Change the fee until the float total is exact, without using ₦1.00. Which fees survive, and what do they have in common?
GOAL: the float total is exact with a fee other than ₦1.00
Rewrite totalKobo(amounts). It takes naira amounts as decimal strings with at most two decimals ("8.29", "0.10") and returns the exact total as an integer number of kobo (a number or a BigInt). The grader includes a day of a million ₦0.10 fees and a payroll file of a million lines of ₦123,456.78.
Integers have limits too. A JavaScript number holds integers exactly up to 2^53 − 1, about ₦90 trillion in kobo; past that, or if you do not want to think about it, use BigInt or a 64-bit integer column. Kahan has a cost besides: four operations per addition, and a compiler told to optimise floating point freely (-ffast-math) may remove the correction as algebraically zero. Integers stop at one problem: dividing ₦100 three ways still leaves a kobo over, which is the residual cent lesson, and knowing how many decimals a currency has is the minor units lesson. Once every amount is an exact integer, the payment ledger can demand that the books sum to zero, not nearly zero.
Ledgers, fee and interest accrual, invoice totals, payout files, reconciliation jobs, spreadsheets exported to code, and every API that sends amounts as JSON numbers. Look for parseFloat, double or float columns, Math.trunc(x * 100), and equality checks with an epsilon.
“Why shouldn't you store money in a float?” Show 0.1 + 0.2 and explain why a tenth has no binary form. Then go further: a long sum drifts, a truncating conversion loses a cent, an equality check fails a reconciliation. Fix with integer minor units or a decimal type, parse amounts from strings at the edge, and say what Kahan summation does and why it is not a substitute.
USED IN
Chapters that build on this lesson.
- Interest, APR, fees and amortisationLending and Credit
- The economics of a loan: cost of funds, risk, operating cost, marginLending and Credit
- Double-entry bookkeeping for engineersPayments
- Money in software: minor units, rounding, currenciesPayments
- Payment messages: ISO 8583 and ISO 20022Payments
- Debugging a problem you have never seenSoftware Engineer
- The first ninety days: the codebase, the team and the first changeSoftware Engineer
- Property-based testing: say what is always true, let the machine huntSoftware Testing and Quality
- Testing money: invariants, reconciliation and evidence for a regulatorSoftware Testing and Quality