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
This entry was posted in howtos and tagged , , , . Bookmark the permalink.

3 Responses to Java: Rounding error from Double to BigDecimal

  1. Hans says:

    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

    • Hans says:

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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s