Wednesday, March 12, 2008

Monetary Calculations In Java


float and double types are not suitable for monetary calculations in Java. If this is the first time you hear this you are in trouble.

Floating point arithmetic which is used to represent float/double variables is inappropriate for exact results calculations. For example it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly. Here is an example:
float s1 = 0;
for (int i = 0; i < 10; i++) {
s1 += 0.10;
System.out.println(s1);
}
This code prints:
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001
1.0000001
Here's another example: (0.1+0.1+0.1) == 0.3 What is the value of this statement true or false? since the sum (0.1+0.1+0.1) is not equal to 0.3 according to JVM, rounding up the sum would result in 4 which is not expected either. I think you got the point. We can not trust float or double variables if we want exact results. Applications that makes money/credit calculations needs exact results. To represent monetary values in Java you should use the BigDecimal class.
BigDecimal bd = new BigDecimal("0");
for (int i = 0; i < 10; i++) {
bd = bd.add(new BigDecimal("0.10"));
System.out.println(bd);
}
This java example prints (as expected):
0.10
0.20
0.30
0.40
0.50
0.60
0.70
0.80
0.90
1.00

1 comments:

Anonymous said...

yazdiklariniz bana ilham veriyor;
ileride ben de sizin gibi olmak istiyorum.. daha cok yazmanizi istiyorum, bekar misiniz?