user1483799 - 1 year ago 72

Java Question

Possible Duplicate:

How to iterate between 0.1f and 1.0f with 0.1f increments in Java?

0.1

0.2

0.3

...

0.9

Here is the code:

`double x = 0.0;`

while ( x<=1 )

{

// increment x by 0.1 for each iteration

x += 0.1;

}

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

0.1

0.2

0.300000000000000000000000004

0.4

0.5

0.6

0.79999999999999999999999999

0.89999999999999999999999999

0.99999999999999999999999999

Answer Source

Welcome to the world of floating point, where 0.1 isn't 0.1. The problem is that many numbers, including 0.1, cannot be represented exactly in a `double`

. So you aren't really adding exactly 0.1 to `x`

each time through the loop.

One approach is to use integer arithmetic and divide by 10:

```
int i = 0;
while (i <= 10) {
double x = i / 10.0;
. . .
i++;
}
```

Another approach is to make `x`

a `BigDecimal`

, where you can specify that you want a particular precision. It basically is doing what the above loop does (an integer plus a scale), but packaged up in a nice class with lots of bells and whistles. Oh, and it has arbitrary precision.