File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Odd behavior with double primitive data type" Watch "Odd behavior with double primitive data type" New topic

Odd behavior with double primitive data type

Tom O'Neil

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;
Oddly enough, the output of this is:
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.
Norm Miller
Ranch Hand

Joined: May 21, 2002
Posts: 56
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

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]
I agree. Here's the link:
subject: Odd behavior with double primitive data type
It's not a secret anymore!