-1

why when i print this code in print statement the output will be not correct.

System.out.println(3.15 - 3);

the output is:

0.1499999999999999

i think the output must be.

0.15
splinter.cell
  • 113
  • 1
  • 7
  • 2
    Floating point arithmetic is not exact. There's a TON of literature on this. – Brick Feb 15 '17 at 20:13
  • why java doing that !! .. and are there any solution for this ? – splinter.cell Feb 15 '17 at 20:18
  • 1
    It's not "Java" doing it. It's fundamental truths about mathematics and finite precision representations of real numbers, which are common in all languages that have a floating point representation. Fixed-point would have related but different issues. The problem is there are an infinite number of real numbers and only finitely many can be represented exactly on 16 bits. Search for "floating point arithmetic." – Brick Feb 15 '17 at 20:23

1 Answers1

-1

System.out.println((float)(3.15 - 3.0)); //the answer is 0.15

System.out.println(3.15f - 3); //the answer is 0.1500001

System.out.println(3.15 - 3.0); //the answer is 0.1499999999999999