Showing posts with label Java floating point. Show all posts
Showing posts with label Java floating point. Show all posts

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:
http://www-128.ibm.com/developerworks/java/library/j-jtp0114/
http://www.javaworld.com/cgi-bin/mailto/x_java.cgi
http://en.wikipedia.org/wiki/IEEE_754

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);