File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Odd behavior with double primitive data type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Odd behavior with double primitive data type" Watch "Odd behavior with double primitive data type" New topic
Author

Odd behavior with double primitive data type

Tom O'Neil
Greenhorn

Joined: Dec 10, 2002
Posts: 1
I am encountering very odd behavior trying to add variables of type double. Using JDK 1.4.1, I have the following basic test class:
public class test {
public static void main (String[] args) {
double a = .3;
double b = .6;
double d = a + b;
System.out.println(d);
}
}
Oddly enough, the output of this is:
0.8999999999999999
Does anyone know why this is occurring? All of the variable values are well within the acceptable range for double, so I'm rather stumped as to why I can't get the proper sum.
Tom
kingofthesquids@yahoo.com
Norm Miller
Ranch Hand

Joined: May 21, 2002
Posts: 56
Hi,
What you are seeing is Floating point numbers of (theoretically) infinite number of decimal places forced to fit in a fixed length word. The computer, when it converts .3 to binary and then squeezes it into the number of bits available, has to drop a little of its value. Same thing happens to .9 The answer you got is very close, but not exact.
If you use a format statement to round it to a single decimal place, the result would be what you expect.
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Take a look at this past conversation in the Cattle Drive forum for two very good links on this topic (that are listed later in the conversation).


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Odd behavior with double primitive data type