2

I want a create a array of values with a interval of 0.2 I used the code :

public class TrialCode {

public static void main(String[] args) {

    float a = -1.0f, b = 0.2f;

    for (int i = 0; i <10; i++) {
        a = a + b;
        System.out.println(a);

    }

}

}

Now the output that i am getting is :

-0.8
-0.6
-0.40000004
-0.20000003
-2.9802322E-8
0.19999997
0.39999998
0.59999996
0.79999995
0.99999994

whereas the output I want is

-0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0

What should I do ?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Danny
  • 51
  • 7

3 Answers3

5

Floating point numbers only work up to a certain precision. For float it is 6-7 significant digits, for double it is 15-16 significant digits. And due to the binary representation simple decimal fractions like 0.1 cannot be represented exactly.

You can round the output to get the results you want:

System.out.printf("%.1f", a);
Henry
  • 42,982
  • 7
  • 68
  • 84
5

If you don't want floating-point arithmetic, then don't use floating-point types. Float and Double aren't the only non-integral Numbers in the Java core library. What you're doing calls for BigDecimal.

import java.math.BigDecimal;

public class TrialCode {

    public static void main(String[] args) {

        BigDecimal a = new BigDecimal("-1.0");
        BigDecimal b = new BigDecimal("0.2");

        for (int i = 0; i < 10; i++) {
            a = a.add(b);
            System.out.println(a);
        }
    }
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
0

You can use something like

new DecimalFormat("#.#").format(0.19999997); //"0.2"
rocketboy
  • 9,573
  • 2
  • 34
  • 36