Point one plus point two
A easy 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.
Highlighted: line 4. Play this one as a puzzle without the answer.
What is wrong
Neither 0.1 nor 0.2 can be represented exactly in binary, and the sum is 0.30000000000000004. Comparing doubles with == is almost always wrong because rounding errors accumulate.
The fix
How to avoid it next time
Compare doubles with a tolerance, or use BigDecimal for decimal values such as money.
Want the background? Read Primitive types and floating point 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
Frequently asked questions
What is the bug in "Point one plus point two"?
Neither 0.1 nor 0.2 can be represented exactly in binary, and the sum is 0.30000000000000004. Comparing doubles with == is almost always wrong because rounding errors accumulate. The faulty line is line 4: if (sum == 0.3) {
How do I fix it?
Replace it with: if (Math.abs(sum - 0.3) < 1e-9) {. Compare doubles with a tolerance, or use BigDecimal for decimal values such as money.
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.