Search code examples
javafloating-pointintfloating-accuracyfloating-point-conversion

different result of int multiplication vs float multiplication


I have this code:

    float number1 = 2f / 12;
    System.out.println(number1);
    int number2 = 6;
    float x = number1 * number2;
    System.out.println(x);

And as output I get:

0.16666667
1.0

Why? When I multiply number1 and number2, number2 should be promoted to float type, and I should get a 0.96

When I modify my code to:

    float number1 = 0.16f;
    System.out.println(number1);
    int number2 = 6;
    float x = number1 * number2;
    System.out.println(x);

I get good result:

0.16
0.96

Why operation float = float * int in first example produces the bad result?


Solution

  • number2 should be promoted to float type

    Number 2 got promoted to float.

    and I should get a 0.96

    You should get 1.0, because:

    2 / 12 * 6 = 2 / 2 = 1

    0.16 * 6 = 0.96

    ... and that's why. It has nothing to do with computational int vs float arithmetic in this case, it's just arithmetic. Do the math first!