0

I tried the following program

class test{
public static void main (String argv[]){
    double x = 0.1;
    double y = 0;
    for (int i =0;i<10 ; i++){
        y=y+x;
        System.out.println (y);
    }
}
}

but it gives the following output

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Why does java7 give this instead of just 0.3 or 0.8 ...!

I tried the following in online java compiler as well http://ideone.com/g0bYad

Pradeep
  • 850
  • 2
  • 14
  • 27

2 Answers2

1

Floating point numbers (including Java's double type) aren't completely precise. See how they encode information for more details. You can see that not all numbers have an exact IEEE 754 64 bit representation

Vyassa Baratham
  • 1,457
  • 12
  • 18
0

Floating point values lack an exact precision. That's their nature. Try using the BigDecimal class.