I’ve got a system that handles account & COD transactions. When a client is paying via COD, I need to round up or round down the cents.
Eg.
Total = 64.42 - rounds to: 64.40
Total = 64.57 - rounds to 64.60
I’m trying to figure out the best way to do this in python and also store the difference in a decimal field in a database.
I’m using DJANGO. I was trying to use the ROUND_05UP part of decimal but I’m not sure how to do it. I wrote a custom filter to display it, but that’s not even working:
@register.filter
def currency(value, arg='en_US', symbol=True):
saved = '.'.join([x for x in locale.getlocale() if x]) or (None, None)
given = arg and ('.' in arg and str(arg) or str(arg) + '.UTF-8')
# Workaround for Python bug 1699853 and other possibly related bugs.
if '.' in saved and saved.split('.')[1].lower() in ('utf', 'utf8'):
saved = saved.split('.')[0] + '.UTF-8'
if saved == (None, None) and given == '':
given = 'en_US.UTF-8'
try:
locale.setlocale(locale.LC_ALL, given)
return locale.currency(value or 0, symbol, True)
except (TypeError, locale.Error):
return ''
finally:
locale.setlocale(locale.LC_ALL, saved)
@register.filter
def currency_cash(value):
value = decimal.Decimal(value)
return currency(value.quantize(Decimal(10) ** -2, rounding=decimal.ROUND_05UP))
Does anyone have a function written that does this?
UPDATE: The reason for this in australia we have no coins less then 5 cents. So 45.55 would stay as 45.55.
Cheers,
Ben
If I understand correctly, the incoming amount is already an exact integer number of cents, and you just want to round to the nearest multiple of 10 cents, but leaving values that already end in
5as they are. Is that correct? Here’s a simple solution using the remainder_near method.Sample output: