1

I'm writing code to calculate how to pay an amount in $100, $50, $20 etc. notes and coins. The code looks something like this (just for $100 at the moment):

hundred = 0
amount = float(input('Value: '))
if amount // 100 >= 1:
    hundred += amount // 100
    amount -= (hundred * 100)
    print(amount)

If I input with just 100, I'm left with 0 which is great. If I input another whole number such as 104, I'm left with 4 which is also correct. However, if I input something like 100.4, instead of being left with 0.4, it prints a very long decimal number (0.4000000000000057) which won't work with the rest of my code. How can I make it so the amount left to pay is only 0.4?

carly m
  • 49
  • 5
  • @blhsing: That duplicate doesn't seem terribly useful: extending the precision isn't going to help here - with binary floating-point, you'll see this effect at any precision. – Mark Dickinson Sep 03 '21 at 09:31
  • @MarkDickinson Not sure why you're talking about a binary floating point when the linked answer specifically uses the `decimal` module and avoids involving any floating point objects. – blhsing Sep 03 '21 at 09:36
  • 1
    @blhsing: My bad; I looked at the question but not the answers. Apologies. – Mark Dickinson Sep 03 '21 at 09:39

0 Answers0