我有一个处理帐户和 COD 交易的系统。当客户通过 COD 付款时,我需要向上或向下舍入美分。
Eg.
Total = 64.42 - rounds to: 64.40
Total = 64.57 - rounds to 64.60
我试图找出在 python 中执行此操作的最佳方法,并将差异存储在数据库中的十进制字段中。
我正在使用 DJANGO。我试图使用十进制的 ROUND_05UP 部分,但我不知道该怎么做。我写了一个自定义过滤器来显示它,但这甚至不起作用:
@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))
有没有人写过这样的功能?
更新:在澳大利亚我们没有少于 5 美分的硬币的原因。所以 45.55 将保持为 45.55。
干杯,本