0

I am calculating with percentage and I just divide a number by 10 and multiply by 100. Before the operation I cast to float.

So:

System.out.println((float)5/10*100);
System.out.println((float)6/10*100);
System.out.println((float)7/10*100);

And I got these:

50.0
60.000004
70.0

The question is why and how did the 60 get 4 millionths?

ampika
  • 143
  • 6
  • 3
    `0.6` is not precisely represented, most likely you meant to round the result to reflect this. `System.out.printf("%.1f%n", 6.0f/10*100);` prints `60.0` – Peter Lawrey Apr 26 '16 at 14:49
  • This is a java problem for long time. You can round it as `result = Math.round(result ×100)/100` to 2 digits behind point. – Mike B Apr 26 '16 at 14:51
  • 2
    This is not a java "problem". It is a matter of how real numbers are represented on a computer in 32 bits, regardless of what language is being used – FredK Apr 26 '16 at 14:56
  • 2
    In addition to what @PeterLawrey said, you should get the correct result when you move the multiplication to the left (`(float)100*6*/10`) because all intermediate results can be represented exactly. – Axel Apr 26 '16 at 14:56

0 Answers0