I am trying to make a program that calculates the equivalent amount of change for a given amount of money. Everything in the program works well until I get to pennies. When I get to pennies, I've done so much floating point arithmetic that the value becomes inaccurate. Here is the output:
As we can see, rather than have 0.2 (which I would divide by 0.1 to get 2, the correct answer), we have 019999999999959064 (which when divided by 0.01 to get the amount of pennies, we get 1 not 2). How can I resolve this issue so that I can get the correct amount of pennies?
You can't. Floating point is not a good choice for modelling exact monetary values.
Either (i), use a long
type and work in pence, or (ii) use a class designed to model money.