1

I am working on a change calculator that accepts five arguments(dollars, quarters, dimes, nickels, pennies) and calculates the total amount of change. When I put change.py in the command line followed by 1 1 1 1 1 I am supposed to get 1.41 as the total but I am getting 1.4100000000000001 instead.When I put in other numbers it works as it should. Can anyone help with this? Thank you!

enter code here
import sys


def change(dollars,quarters,dimes,nickels,pennies):

dollars = int(float(dollars))
quarters = int(float(quarters))
dimes = int(float(dimes))
nickels = int(float(nickels))
pennies = int(float(pennies))

total = (dollars * 1.00) + (quarters * .25) + (dimes *.10) + (nickels * .05) + (pennies * .01)

return total
round(total)

dollars = sys.argv[1]
quarters = sys.argv[2]
dimes = sys.argv[3]
nickels = sys.argv[4]
pennies = sys.argv[5]    
  
total = change(dollars,quarters,dimes,nickels,pennies)
print('The total value of your change is ',(total)) 
scwat
  • 45
  • 5
  • 1
    See https://stackoverflow.com/questions/588004/is-floating-point-math-broken and https://0.30000000000000004.com/#python-3 – Alexander Feb 07 '22 at 21:17
  • 5
    Don't use floating point for money. Either use integer pennies or use the `Decimal` package. – Barmar Feb 07 '22 at 21:17

1 Answers1

0

This is called a floating-point error (see this question). A simple solution would be to just round your numbers:

return round(total, 2)
econbernardo
  • 98
  • 1
  • 7
  • Which may not help, as `1.41` may not be exactly representable in binary floating point. – Fred Larson Feb 07 '22 at 21:20
  • Thank you @econbernardo ! I added a $. I want it to be $1.41 but I am getting a space $ 1.41. How do I eliminate the space? – scwat Feb 07 '22 at 21:30
  • You can try: `print(f'The total value of your change is ${total})` (this is called an f-string). – econbernardo Feb 07 '22 at 21:40
  • @econbernardo Thank you :) It worked. I know about f strings but I am just learning everything and so I get worried something I do will mess everything up. I though about using strip() somehow but that would probably make it more complicated. – scwat Feb 07 '22 at 21:53
  • @scwat Glad I could help! – econbernardo Feb 07 '22 at 22:10