Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I improve my coin change calculator so that the total is 1.41 instead of 1.4100000000000001?

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)) 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

return round(total, 2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading