BigDecimal.ROUND_HALF_UP widely used in Java to compute and display currency values.

Let look on next example.

We have some price: \$1498.00 (doesn’t matter what it is). And some fee (also doesn’t matter who get it) that counted by formula :

fee = price * 0.075 + 0.99

so, we have next java code

`double fee = (Double.parseDouble("1498") * 0.0775 ) + 0.99;`

`BigDecimal feeRounded = new BigDecimal(fee).setScale(2, BigDecimal.ROUND_HALF_UP);`

and we expect result in feeRounded: 117.09 because fee = 117.085  . And for another prices all properly works : we get exactly what we expect to get.

But we get 117.08   !!  Why?

Because new BigDecimal(fee) is not equal 117.085  .

It equals 117.08499999999999999937422392… and so on. And rounded to 117.08 .

To work properly code must be changed to create BigDecimal from String not from double.

`double fee = (Double.parseDouble("1498") * 0.0775) + 0.99;`

`BigDecimal feeRounded = new BigDecimal(fee + "").setScale(2, BigDecimal.ROUND_HALF_UP);`

Filed under: java

Like this post? Subscribe to my RSS feed and get loads more!