-3
System.out.println("3.14 - 5 = " + (3.14 - 5));

This statement shows 3.14 - 5 = -1.8599999999999999 in console when the answer is -1.86.

How would I be able to fix this error and what is the reason for the wrong answer being printed in the first place?

Thanks for answering my question, even though it's probably very simple :/.

Kyle
  • 183
  • 1
  • 1
  • 12

1 Answers1

1

When the decimal number is converted to binary it is approximated and not exact.So the subtraction is not exact.

3.14 is converted to binary ,so is 5 When the result reconverted to decimal it is not exact.Read about converting decimals to binary from this link :

http://cs.furman.edu/digitaldomain/more/ch6/dec_frac_to_bin.htm

Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29