0

This is my code:

cost = float(input("How much was the cumulative cost?\n"))
amount_given = float(input("How much did the customer give you?\n"))

change = amount_given - cost

possible_change = [5, 2, 1, 0.50, 0.20, 0.10]
change_to_give = []

for i in possible_change:

    while cost >= i:

        change = change - i
        change_to_give.append(i)

print(change_to_give)

The main issue I seem to be coming across is that the change variable ends up with a very peculiar number often many decimal places long.

I've probably made a silly mistake but I just can't seem to find it!

  • 2
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Jongware May 01 '16 at 09:29
  • 2
    Do not use floating point when dealing with money... – Bakuriu May 01 '16 at 09:31
  • You did not make an error, the computer does. (But unwillingly - see the proposed duplicate for the longer story.) A good fix is to calculate evrything in *cents*; i.e., not using floating point. – Jongware May 01 '16 at 09:31
  • you loop while `cost` is `greater` than `i` when you should be using `change` – TheLazyScripter May 01 '16 at 09:31
  • 2
    Other than that the change can become negative (the while loop never terminates, right)? Maybe you meant instead of cost to put change. – GrigorisG May 01 '16 at 09:35
  • 3
    I don't always make change, but when I do, I prefer [`divmod()`](https://docs.python.org/3.5/library/functions.html#divmod). – TigerhawkT3 May 01 '16 at 09:39
  • For a financial application there are accounting rules for types of rounding, depending on what you are doing. In general it is easier to deal with pence, or cents, or whatever is the lower denomination in your currency. So don't convert the string to `float`, take the decimal point out. And decide what you are going to do with the fractions. – cdarke May 01 '16 at 09:41
  • 1
    @cdarke - It's worth pointing out that you also have to handle the case where a user entered a dollar value with no cents, so there's going to be some mess involved in ensuring you're parsing the right number. – TigerhawkT3 May 01 '16 at 09:55

1 Answers1

1

As TheLazyScripter has said in the comments.

while cost >= i

should be

while change >=i

Also, as Rad Lexus said in the comments, do this in cents instead of float. float is asking for a rounding error infinite loop.

Solution

Below incorporates both of those points

cost = int(float(input("How much was the cumulative cost?\n")) * 100)
amount_given = int(float(input("How much did the customer give you?\n")) * 100)

change = amount_given - cost

possible_change = [int(j * 100) for j in [5, 2, 1, 0.50, 0.20, 0.10]]
change_to_give = []

for i in possible_change:

    while change >= i:

        change = change - i
        change_to_give.append(i)


change_to_give = [j / 100. for j in change_to_give]        

print(change_to_give)
piRSquared
  • 285,575
  • 57
  • 475
  • 624