# Thread: Strange division of doubles

1. Member
Join Date
Oct 2011
Posts
5
Rep Power
0

## 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?

2. Moderator
Join Date
Jul 2010
Location
California
Posts
1,641
Rep Power
9

## 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.

3. Member
Join Date
Oct 2011
Posts
5
Rep Power
0

## 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.