Thursday 31 July 2008

working with finances in java

When writing a Java application that is dealing with finances, it is very wise to use BigDecimal class instead of float or double.

This is Sun’s official advice:

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html


BigDecimal class provides methods and properties for hendling numbers in very precise manner.

Let’s see how to use this class:

First of all, create BigDecimal object. For example:

BigDecimal result = new BigDecimal(0.00);


And let’s say we have two values to substract or multiply:

1234.123456789776 and 0.3888377362


In order to do this , java.math.BigDecimal has



BigDecimal add(BigDecimal augend) method for substracting numbers.

or

BigDecimal multiply(BigDecimal multiplicand) method for multiplying numbers


These, offcourse, are not the only method in this class. There are also other methods for mathematical operations. This was just taken for example…

Code:

result = (new BigDecimal(1234.123456789776)).add(new BigDecimal(0.3888377362));


To display the result, you can use the BigDecimal class's toString() method:

System.out.println(result.toString());


and the result would be:

1234.512294525975900694181319749986869283020496368408203125

Or you can display result using, for example BigDecimal class's doublevalue() method:

System.out.println(Double.toString(result.doubleValue()));

Which gives result:

1234.512294525976


Great thing about this class is ability to complitely control how some number needs to be rounded. In order to do this, we can use BigDecimal class's setScale() method.

In order to use it, you just need to specify how many decimal places you would like your number to have, and the logic of rounding it.


There are a lot ways to round it:


ROUND_CEILING
ROUND_DOWN
ROUND_FLOOR
ROUND_HALF_DOWN
ROUND_HALF_EVEN
ROUND_HALF_UP


and many more…

For example, if we want to round our result to 2 decimal places, and to round it with ROUND_HALF_UP method, call:

result = result.setScale(2,BigDecimal.ROUND_HALF_UP);


and then, the result will be:

1234.51

for

System.out.println(result.toString());

and for

System.out.println(Double.toString(result.doubleValue()));

I never used this class before, untill today, when I noticed some wrong results while working on some software that needed very presice results…

BigDecimal class solved my problems…