I know the following behavior is an old problem, but still I don’t understand.
System.out.println(0.1 + 0.1 + 0.1);
Or even though I use BigDecimal
System.out.println(new BigDecimal(0.1).doubleValue()
+ new BigDecimal(0.1).doubleValue()
+ new BigDecimal(0.1).doubleValue());
Why this result is: 0.30000000000000004 instead of: 0.3?
How can I solve this?
What you actually want is
The
new BigDecimal(double)constructor gets all the imprecision of thedouble, so by the time you’ve said0.1, you’ve already introduced the rounding error. Using theStringconstructor avoids the rounding error associated with going via thedouble.