BackendBench
Coffee
Spot the Bug #70

One third throws

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: 5

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

What is wrong

Dividing 10.00 by 3 has no terminating decimal expansion. Without a scale and rounding mode BigDecimal.divide throws ArithmeticException: Non-terminating decimal expansion.

The fix

return total.divide(BigDecimal.valueOf(people), 2, java.math.RoundingMode.HALF_EVEN);

How to avoid it next time

Always pass a scale and a RoundingMode to divide. Decide how remainders (the missing cent) are allocated.

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โ† #69#71 โ†’

Frequently asked questions

What is the bug in "One third throws"?

Dividing 10.00 by 3 has no terminating decimal expansion. Without a scale and rounding mode BigDecimal.divide throws ArithmeticException: Non-terminating decimal expansion. The faulty line is line 5: return total.divide(BigDecimal.valueOf(people));

How do I fix it?

Replace it with: return total.divide(BigDecimal.valueOf(people), 2, java.math.RoundingMode.HALF_EVEN);. Always pass a scale and a RoundingMode to divide. Decide how remainders (the missing cent) are allocated.

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