Thursday, December 28, 2006

Dealing with currency calculations

Many novice developers use 'float' and 'double' data-types to represent dollars and cents. This is dangerous as float/double calculations always involve rounding off and precision errors.

More info can be found at the following links:

Currency values require exactness. Hence use the 'BigDecimal' class in Java for handling currencies. Here is some code snippet:

//Get the base value of the policy and store it in a BigDecimal object
BigDecimal d = new BigDecimal("1115.32");

//get the extra's multiplier from database
BigDecimal multiplier = new BigDecimal("0.0049");

//Do the multiplication - use methods of Big Decimal
BigDecimal d2 = d.multiply(multiplier);
System.out.println("Unformatted no scale: " + d2.toString());

//Set the scale (2 decimal places) and round-off mode
d2 = d2.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("Unformatted with scale: " + d2.toString());

NumberFormat n = NumberFormat.getCurrencyInstance(Locale.UK);
double money = d2.doubleValue();
String s = n.format(money);
System.out.println("Formatted: " + s);