Find the bug · #26 · Numbers Easy JavaScript
Paid bills still show as unpaid
A bill splitter marks bills paid when payments add up, but some fully paid bills stay unpaid.
On this page
The report
A bill-splitting app marks a bill as paid when everyone’s payments add up to the total. A ₹0.30 bill paid as ₹0.10 and ₹0.20 stays “unpaid” forever.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Marks the bill paid when the payments (in rupees) add up to the total.
function isPaidInFull(total, payments) {
const paid = payments.reduce((sum, p) => sum + p, 0);
return paid === total;
}Read it, then pick a line.
Type 0.1 + 0.2 into the console. What do you get?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
console.log(isPaidInFull(0.3, [0.1, 0.2]));
console.log(isPaidInFull(100.5, [50.25, 50.25]));It prints
false true
It should print
true true
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 compares two floating-point numbers with ===. Amounts like 0.1 can’t be stored exactly in binary, so 0.1 + 0.2 is 0.30000000000000004, not 0.3, and the bill never counts as paid. Compare whole paise instead; better still, keep money in integer paise everywhere.
The fix
1// Marks the bill paid when the payments (in rupees) add up to the total.2function isPaidInFull(total, payments) {3 const paid = payments.reduce((sum, p) => sum + p, 0);4 return paid === total;4 return Math.round(paid * 100) === Math.round(total * 100);5}How you’d find it
- Reproduce with the reported bill: 0.1 + 0.2 against 0.3 says unpaid. Round amounts like 50.25 + 50.25 work.
- Print
paid:0.30000000000000004. The sum is a hair off. - That’s floating point: most decimal fractions have no exact binary form. Equality on floats is the bug.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.equal(isPaidInFull(0.3, [0.1, 0.2]), true);
assert.equal(isPaidInFull(10, [3.3, 3.3, 3.3]), false);Where else this bites
- Money in a database should be
DECIMALor integer paise, neverFLOAT. - Python and Java doubles behave the same way; use
DecimalorBigDecimal.