### Thread: When I add Doubles, unexpected result!

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
5
Rep Power
0

#### When I add Doubles, unexpected result!

When I add 3 doubles (1.1,2.1,3.1) , I get 6.300000000000001

This is obviously a rookie error - could someone enlighten me please?

Code:
```double x,y,z,total;
x = Double.parseDouble(JOptionPane.showInputDialog("Please enter a number"));
y = Double.parseDouble(JOptionPane.showInputDialog("Please enter a number"));
z = Double.parseDouble(JOptionPane.showInputDialog("Please enter a number"));
total = x + y + z;
System.out.println(total);
}```
2. You haven't done anything wrong. The reason for the result is that there are some decimal numbers which cannot be converted exactly into binary.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
5
Rep Power
0
Originally Posted by bullet
You haven't done anything wrong. The reason for the result is that there are some decimal numbers which cannot be converted exactly into binary.
Thanks - is rounding the only solution? Obviosuly in many scenarios, the total I came up with would be unacceptable.
4. Originally Posted by basil54
Thanks - is rounding the only solution? Obviosuly in many scenarios, the total I came up with would be unacceptable.
There are generally two workarounds to floating point issues.
1) Do your work as plain integers and then divide and round at the last moment. For example, the above would instead be:
Code:
`(11+21+31)/10`
or
2) Use an arbitrary precision math library designed for exact number representation. I don't really know Java so I can't offer a specific suggestion as to what to use for this, but a quick google suggests the java.math.BigDecimal object is a possibility.