I'm trying to create a function that will divide a number into categories based on a specified percent (okay, a budget.)
I've taken the divided floats, grabbed a test truncate function off the web, and truncated everything after the hundredth place. This is to prevent the sum of all the categories being greater than the initial amount. Then I subtract the total sum of the categories from the initial amount to get a "remainder," which in my example should be 0.03, or 3 cents.
def budget_calc(amount):
budget = {"t":0.10,
"c":0.50,
"s":0.20,
"e":0.05,
"c/m":0.05,
"tr":0.05,
"o":0.03,
"g/d":0.02}
def truncate(x, d):
return int(x*(10.0**d))/(10.0**d)
def multp(key):
cate = truncate(amount * budget.get(key), 2)
return cate
new_amounts = {'t': multp('t'),
'c': multp('c'),
's': multp('s'),
'e': multp('e'),
'c/m': multp('c/m'),
'tr': multp('tr'),
'o': multp('o'),
'g/d': multp('g/d')}
remainder = amount - sum(new_amounts.values())
new_amounts.update(remainder = remainder)
return new_amounts
This is what I'm getting:
budget_calc(148.72)
{'t': 14.87,
'c': 74.36,
's': 29.74,
'e': 7.43,
'c/m': 7.43,
'tr': 7.43,
'o': 4.46,
'g/d': 2.97,
'remainder': 0.029999999999972715} #<-- this number should only contain two decimal points
So somewhere along the line the "truncate" function is only displaying the truncated number, not actually getting rid of the excess digits? The math in there is wrong as well, 148.72 - the sum of all the truncated numbers (148.69) should be 0.03. That's what it seems like, an additional diagnosis would be great.
No comments:
Post a Comment