Java: Rounding error from Double to BigDecimal

Today’s amusement in my job:

Rounding error from Double to BigDecimal, see java docs for public BigDecimal(double val).

Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625

 

Workaround 1: Convert Double to String before converting to BigDecimal, as suggested in the java docs for BigDecimal

BigDecimal b = new BigDecimal(Double.toString(double));

 

Workaround 2: Round!
Double d = ...; // your (rounded) value
BigDecimal b = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);

.

Another problem with Double in Java: http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/

Advertisements