Reputation: 19399
Working on a django project. On my payment model I have a simple def save
def save(self, *args, **kwargs):
self.amount_change = self.amount_due - self.amount_paid
return super(Payment, self).save(*args, **kwargs)
If my amount_change comes to -455.50
I'd like to return change as
What I'd like to do is breakdown the amount_change into the money denominations that I have and return the change to the client with the correct notes and or coins. My denominations are [200, 100, 50, 20, 10, 5, 1, 0.5]
How do I go about doing this? Any help is appreciated.
Upvotes: 0
Views: 3615
Reputation: 10676
Building upon this answer, I believe this is returning the desired results:
from collections import Counter
def change(amount):
money = ()
for coin in [200, 100, 50, 20, 10, 5, 1, 0.5]:
num = int(amount/coin)
money += (coin,) * num
amount -= coin * num
return Counter(money)
Input and output:
>>> c = change(455.50)
>>> print c
Counter({200: 2, 0.5: 1, 50: 1, 5: 1})
Edit: If you need to pass in a negative number, create a new variable inside the function by multiplying by -1 and use it inside the function instead of amount
Upvotes: 1