Friday, October 31, 2008

Manage amounts in Java with BigDecimal

What result do you expect from this sum?
double x = 0.009;
double y = 0.001;
double z = x + y;

The correct value is 0.01 but in Java the result is 0.009999999999999998!

This is the reason why the JDK provides the class BigDecimal: use it always for financial calculation!

Anyway you have to pay some attention to 5 simple rules:
1) Don't forget the operations return always the new value, for example don't do this:
amount.add( thisAmount );

because the right way is
amount = amount.add( thisAmount );


2) When you create a new object use the string constructor, that means new BigDecimal("10.50") instead of new BigDecimal(10.50).

3) To compare never use the .equals() method, because it will compare also the scale and not only the mathematical value. Instead, use the .compareTo() and .signum() methods.

4) When dividing BigDecimals, be careful to specify the rounding in the .divide(...) method. Thus, you should always do:
a = b.divide(c, decimals, rounding);


5) Finally the gold rule for everything: read carefully the API Reference!

No comments: