0

I write below code in java

double scale=1.0;
for(int i=0;i<6;i++){
    scale=scale/10;
}
System.out.println(scale);

Now out put of this is 1.0000000000000002E-6 which seems to be incorrect, but if I loop 5 times then output is correct as below
1.0E-5

Can any body tell me why this is and how can I remove this.

agarwal_achhnera
  • 2,582
  • 9
  • 55
  • 84

3 Answers3

2

This is floating point precision problem. Use BigDecimal instead of double.

    BigDecimal scale=BigDecimal.ONE;
    for (int i = 0; i < 6; i++) {
        scale = scale.divide(BigDecimal.valueOf(10));
    }
    System.out.println(scale);
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

Because even 0.1 is not representable as an exact double value. These errors sum up and show in the result.

Axel
  • 13,939
  • 5
  • 50
  • 79
-3

change i initialization.

double scale=1.0;
for(int i=1;i<6;i++){
    scale=scale/10;
}
System.out.println(scale);

now our code will enter the for for values i = [1, 2, 3, 4, 5], its 5 times

RamonBoza
  • 8,898
  • 6
  • 36
  • 48