0

Possible Duplicate:
Java: Calculations returning wrong answer?

Please explane why following program not giving correct output.

class Test
{
    public static void main(String aa[])
    {
        float a=16.15 f;
        float b =10.0f;

        float c =a-b;
        System.out.println(c);
    }
}

/****************/ Out Put:-6.1499996

Community
  • 1
  • 1
Deepesh Uniyal
  • 841
  • 3
  • 16
  • 37

4 Answers4

1

The problem lies with floats themselves, rather than your code, as per http://en.wikipedia.org/wiki/IEEE_floating-point_standard

For this case, consider either using doubles or BigDecimals

Ina
  • 4,220
  • 5
  • 28
  • 43
0

That's a perfectly normal consequence of floats not being able to store decimal values exactly.

Louis Wasserman
  • 182,351
  • 25
  • 326
  • 397
0

Because floats, being base-2 cannot exactly represent 16.15 and therefore the result of the subtraction is not exactly -6.15.

tjltjl
  • 1,479
  • 8
  • 18
-1

The type float does not have good enough precision to return -6.15. double may not be enough either, floating point computations always have some margin of error.

Erik Ekman
  • 2,031
  • 12
  • 13