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/

Advertisement

3 thoughts on “Java: Rounding error from Double to BigDecimal

  1. Round error ist kein error, sondern so dokumentiertes Verhalten:
    “Translates a double into a BigDecimal which is the exact decimal representation of the double’s binary floating-point value.” (Javadoc)
    Ps: Dein Tip zur JPA-Annotationen hat mir sehr geholfen. Danke

    1. Es gibt einen netten Java-Puzzler zu genau dem Problem.

      (kannst zu 7 Minuten vorspulen, aber der ganze Vortrag ist super)

Comments are closed.