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

4
  • 5
    docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Commented Dec 6, 2012 at 22:04
  • floating points calculations can't results in exact precision for .15. Commented Dec 6, 2012 at 22:04
  • 1
    There should be some canonical standard answer for this type of questions, no day passes without a dozen of 'em :-( Commented Dec 6, 2012 at 22:05
  • When using floats, add an error margin epsylon, and check for c < epsylon. Commented Dec 6, 2012 at 22:08

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

-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.

1 Comment

It's a question of which base it is in

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.