Saturday, March 31, 2012

Some problems of float and double variables in java

You must not use the float or double datatype for accurate calculations.
At java programming, it doesn't get exact number to use the float or double datatype.

For example, if you had 1.03 dollars and used 42 cents, you remained 61 cents.
Using java programming answers as follows.


System.out.println(1.03 - .42);

---------- Execute ----------
0.6100000000000001

Not exactly what you want. 
Because the float and double was designed for science and engineering, it calculates so fast as an approximate value. 
So the float and double variables are imprecise. 

What you use for accurate calculations?
The answer is int, long, and bigdecimal

I refer to the book of effective java programming language guide.



No comments:

Post a Comment