February 18th, 2014, 03:15 PM
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?
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;
February 18th, 2014, 07:54 PM
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.
February 18th, 2014, 08:42 PM
Thanks - is rounding the only solution? Obviosuly in many scenarios, the total I came up with would be unacceptable.
Originally Posted by bullet
February 18th, 2014, 09:01 PM
There are generally two workarounds to floating point issues.
Originally Posted by basil54
1) Do your work as plain integers and then divide and round at the last moment. For example, the above would instead be:
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.
Recycle your old CD's, don't just trash them
If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud