Recently I saw a weird floating issue in Java application which made our currency calculation wrong. Can you guess what would be the output of the below code?
System.out.println(38.0 - 26.6);
With help of google search found this error is related to floating point arithmetic calculation. Sun recommends to use BigDecimal for currency calculation in Java. For example above code can be changed as below:
System.out.println(BigDecimal.valueOf(38.0).subtract(BigDecimal.valueOf(26.6)));
For database updates also BigDecimal object can be used as below:
PreparedStatement ps = connection
.prepareStatement("UPDATE AccountBill SET AmountPaid=? WHERE BillNo=?");
ps.setBigDecimal(1, BigDecimal.valueOf(0.01));
ps.setInt(2, 12345);
ps.executeUpdate();
Lesson Learned:
a) Don’t use float/double for exact values like money/currency.
b) Use BigDecimal for all currency values representation and its calculation.
I don’t have patience to go through below article, seems it explain the floating point arithmetic issue in detail.

Leave a comment