-1
double basicPay = 1999.0;
        double hra = 145.0;
        float experience = 3.0f;
        double percentage;
        if(experience<3)percentage = 0;
        else if(experience>=3 && experience<5)percentage = 5;
        else if(experience>=5 && experience<10)percentage = 7;
        else percentage = 12;
        double salary = (basicPay + hra + basicPay*(percentage/100));
        System.out.println(salary);

This shows output as 2243.95

But if I change

double salary = (float)(basicPay + hra + basicPay*(percentage/100));

The answer now is 2243.949951171875

Why is this happening?

1 Answers1

0

This is problem not related to Java, but to the standard of floating point numbers and their precision. Not all numbers can be represented with float. Instead of the exact value the floating point is going to get a value that is a closest approximation of the real value in floating point format. double has much more bytes to store the data, so it's more precise.

I won't go into explaining the whole thing because I believe there is plenty of resources which explain it very well, google floating point precision.

Filip
  • 609
  • 7
  • 18
  • Java is partly responsible here; its default output of 2243.95 does not show the true value that was computed. If it did, it would be more apparent to people that both calculations include rounding errors. – Eric Postpischil May 20 '21 at 19:12