Precision of double type variable causing weird decimal issues.
Posted on 2004-08-11
-JDK VERSION 1.3.1_03
I have a custom class that has a double variable. The class also has a method to add another object of the same class to itself (by adding the double variables and storing the result in the calling object's variable). For each of the following numbers (below example), the class is created, the number is set for the field, and then stored in the hashtable. Each subsequent time the object is stored, it is removed from the hashtable, the add method is called on the stored object, and then put back into the hashtable. The problem is that when these objects later used to create a new ArrayList by calling the Hashtable.values() method the sum of these numbers has an additional 0.0000000000002. I iterate through the arraylist and call the .getDoubleVariable() method for each object. Oddly enough, I get the following value: 1244.8000000000002 (the ArrayList index would only have 1 entry in this example).
AnObject o= new AnObject();
Can anyone explain to me why this is happening? The answer I expect is 1244.80. It seems odd that it would throw in such a small decimal value somewhere. This is a pain since it obviously is not giving me the value I expect.