-1

So the goal is to convert money to the possible coins you can have

my code so far:

 def make_change(amount):
  q_f = (amount // .25)
  d_f = (amount - (q_f * .25)) // .10
  n_f = (amount - ((q_f * .25) + (d_f * .10 ))) // .05
  p_f = (amount - ((q_f * .25) + (d_f * .10)  + (n_f * .05))) //.01
  q = int(q_f)
  d = int(d_f)
  n = int(n_f)
  p = int(p_f)
  change = "" + str(q) + " quarter(s), " + str(d) + " dime(s), " + str(n) + " nickel(s) and 
  " + str(p) + " penny(ies) "
  return (change)

the problem is, say you input make_change(.19), the pennies are 3 instead of 4 because of the round-off error, is there a different way to write my code so the round-of error won't happen?

  • 2
    The solution is to never use floating point numbers for currency. Use integers of pennies. – DisappointedByUnaccountableMod Nov 01 '20 at 17:39
  • 1
    Does this answer your question? [Displaying total amount including money calculations to user](https://stackoverflow.com/questions/12938935/displaying-total-amount-including-money-calculations-to-user) – wjandrea Nov 01 '20 at 18:51

1 Answers1

1

As @barny mentioned, try to stay away from floats with currency. You can do this by multiplying the amount by 100 and use subtraction to process the coins.

Try this code:

def make_change(amount):
   amount = int(amount * 100)  # pennies are integers
   coins = [25, 10, 5, 1]  # coin values * 100
   chg = [0]*len(coins)  # coin counts
   for i,c in enumerate(coins):  # each coin
      while amount - c >= 0:   # subtract coins from largest to smallest
         amount -= c   # deduct coin amount
         chg[i] = chg[i] + 1   # add to coin count
   change = str(chg[0]) + " quarter(s), " + str(chg[1]) + " dime(s), " + str(chg[2]) + " nickel(s) and " + str(chg[3]) + " penny(ies)"
   return change


lst = [0.19, 1.37, 2.42, 2.31, 1.09]

for a in lst:
   print(a, '=', make_change(a))

Output

0.19 = 0 quarter(s), 1 dime(s), 1 nickel(s) and 4 penny(ies)
1.37 = 5 quarter(s), 1 dime(s), 0 nickel(s) and 2 penny(ies)
2.42 = 9 quarter(s), 1 dime(s), 1 nickel(s) and 2 penny(ies)
2.31 = 9 quarter(s), 0 dime(s), 1 nickel(s) and 1 penny(ies)
1.09 = 4 quarter(s), 0 dime(s), 1 nickel(s) and 4 penny(ies)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mike67
  • 11,175
  • 2
  • 7
  • 15
  • can you see if it works in here rq? https://codingbat.com/prob/p282862?parent=/home/bryce.hulett@hotmail.com I'm in the car rn so I can't access the things I need on my phone –  Nov 01 '20 at 18:32
  • A minor change was needed, but it works in codingbat – Mike67 Nov 01 '20 at 18:51