BackendBench
Coffee
Spot the Bug #68

A hundred dimes that do not make ten dollars

A medium Java puzzle in the floating point and money family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumFloating point and moneybuggy line: 3

Highlighted: line 3. Play this one as a puzzle without the answer.

What is wrong

Adding 0.10 one hundred times produces 9.99999999999998 because 0.1 is not exactly representable. For money these errors accumulate and make totals, tax and reconciliation disagree by a cent.

The fix

BigDecimal total = BigDecimal.ZERO; for (int i = 0; i < 100; i++) total = total.add(new BigDecimal("0.10"));

How to avoid it next time

Use BigDecimal built from strings, or integer cents, for currency.

Want the background? Read BigDecimal and money in the Java concepts library.

About floating point and money

Binary floating point cannot represent most decimal fractions exactly, so equality checks and money calculations with double drift. BigDecimal needs its own care: construct it from strings and always give a scale and rounding mode.

In code review: Flag double or float used for currency, and any == or != on floating point. Check how BigDecimal values are created and rounded.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #67#69 โ†’

Frequently asked questions

What is the bug in "A hundred dimes that do not make ten dollars"?

Adding 0.10 one hundred times produces 9.99999999999998 because 0.1 is not exactly representable. For money these errors accumulate and make totals, tax and reconciliation disagree by a cent. The faulty line is line 3: double total = 0;

How do I fix it?

Replace it with: BigDecimal total = BigDecimal.ZERO; for (int i = 0; i < 100; i++) total = total.add(new BigDecimal("0.10"));. Use BigDecimal built from strings, or integer cents, for currency.

How do I catch floating point and money in code review?

Flag double or float used for currency, and any == or != on floating point. Check how BigDecimal values are created and rounded.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need