Multiplying two numbers using BigDecimal returns a wrong value

Executing the following code:

new BigDecimal(0.06 * 3).toString()

returns 0.179999999999999993338661852249060757458209991455078125 instead of 0.18.

Executing

new BigDecimal(0.06).multiply(new BigDecimal(3)).toString() 

returns the same result.

How is this possible?

Jon Skeet
people
quotationmark

You're not multiplying two numbers using BigDecimal. You're multiplying them using double arithmetic, and passing the result to the BigDecimal constructor.

You want:

new BigDecimal("0.06").multiply(new BigDecimal("3")).toString()

Note that you do want the values in strings - otherwise you're using the double value for 0.06, which isn't exactly 0.06... you've lost information before you start. (You don't really need the string form of 3, but I've done so for consistency.)

For example:

System.out.println(new BigDecimal(0.06));

prints

0.059999999999999997779553950749686919152736663818359375

people

See more on this question at Stackoverflow