Skip to content
Advertisement

Cash to Change in Java

I am new to Java and was trying to write code that would tell you how much change you would receive for a given amount of money (in minimum number of coins). For example $0.31 would give 1 quarters, 0 dimes, 1 nickels, 1 pennies.

I got to a point where my code seemed to work. However, while most values work, specifically any multiple of 0.41 doesn’t work (ex. 0.41, 0.82 …). For example $0.41 results in 1 quarters, 1 dimes, 1 nickels, 0 pennies, which only adds up to $0.40.

Here is my code:

JavaScript

I was using the check_Change function to check my results.

I don’t know why this doesn’t work and why it is only certain numbers.

Advertisement

Answer

When you are subtracting from a double – the internal representation is not exact – running your code and printing out the amount every time you subtract yields the following:

JavaScript

As you can see the binary representation of the double is not exact…

try convert to an int (i.e. multiply by 100) then do the calculations

JavaScript

output

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement