Handling currency calculations in Java business application
March 29, 2009 6 Comments
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:
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();
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.