So I am currently reading a book on learning java and a program outlined inside the book is giving me some trouble. Specifically when I run the program to compute the amount of dollars and change that I should have from 9.87, I get change from what I would get as if I typed 9.86. However when I type 9.86 I get the correct amount of change. As far as I know this only happens with some amounts that end in .87 such as 8.87, although it works for 6.87 fine. This is the book introduction to java programming 8th edition and since it was a book that was written by a professional I am confused as to what the error could be. I have tried running it in cmd and eclipse and both seem to show the fault.
PasteBin Link:
I’m almost certain that you’re being bitten by a poor understanding of how floating point numbers work. You can no more represent 0.1 exactly in binary any more than you can 1/3 in decimal. Then, on top of that, IEEE floating point numbers can’t have more than 17 digits of precision for doubles.
It’s not a bug in Java or your code.
Money is a classic example of something that shouldn’t be represented with decimal numbers.
Write a Money class with integer dollars and cents and use that when you learn enough Java: