BackendBench
Coffee
Spot the Bug #69

BigDecimal made from a double

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

The double 0.1 is already inexact before BigDecimal sees it, so the constructor preserves the whole binary value: 0.1000000000000000055511151231257827... The result carries the representation error into your exact arithmetic.

The fix

BigDecimal tenth = new BigDecimal("0.1"); // or BigDecimal.valueOf(0.1)

How to avoid it next time

Construct BigDecimal from a String or with BigDecimal.valueOf, never from a double literal.

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โ† #68#70 โ†’

Frequently asked questions

What is the bug in "BigDecimal made from a double"?

The double 0.1 is already inexact before BigDecimal sees it, so the constructor preserves the whole binary value: 0.1000000000000000055511151231257827... The result carries the representation error into your exact arithmetic. The faulty line is line 5: BigDecimal tenth = new BigDecimal(0.1);

How do I fix it?

Replace it with: BigDecimal tenth = new BigDecimal("0.1"); // or BigDecimal.valueOf(0.1). Construct BigDecimal from a String or with BigDecimal.valueOf, never from a double literal.

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