Strange division of doubles

• 10-10-2011, 04:21 PM
Tien
Strange division of doubles
I have the following very simple Java code:

double dr = 0.1;
double x;
cora = x/dr;

In a for loop x goes from 0.2 to 0.35. When I divide them, the first two results are perfect, but the next results are not "rounded" but end at .999999999999996.

Results from Java code:

cora: 2.0
cora: 2.5
cora: 2.9999999999999996
cora: 3.4999999999999996

This is a problem because I use (int) to round the results to their lower integer value.

(int) 2.99...6 = 2 but it should be (int) 3.0 = 3

What goes wrong?
• 10-10-2011, 04:47 PM
doWhile
Re: Strange division of doubles
It is a fundamental result of floating point math. If you need a rounded int out of it, use the Math.round() method.
• 10-10-2011, 05:37 PM
Tien
Re: Strange division of doubles
But how do I solve the problem of the division itself? I need the true value of the division, not only for the rounding, but also for a bunch of boundary conditions. If you take, for example, the condition "if (x>=3.0)" element 2.99...6 is excluded, while it should be included since it is actually 3.0! I need this division quite often, so I really need to solve it.
• 10-10-2011, 06:12 PM
JosAH
Re: Strange division of doubles