from django import template
from django.conf import settings
register = template.Library()
@register.filter()
def currency(value):
symbol = '$'
thousand_sep = ''
decimal_sep = ''
# try to use settings if set
try:
symbol = settings.CURRENCY_SYMBOL
except AttributeError:
pass
try:
thousand_sep = settings.THOUSAND_SEPARATOR
decimal_sep = settings.DECIMAL_SEPARATOR
except AttributeError:
thousand_sep = ','
decimal_sep = '.'
intstr = str(int(value))
f = lambda x, n, acc=[]: f(x[:-n], n, [(x[-n:])]+acc) if x else acc
intpart = thousand_sep.join(f(intstr, 3))
return "%s%s%s%s" % (symbol, intpart, decimal_sep, ("%0.2f" % value)[-2:])
Comments
In Your code even if settings.DECIMAL_SEPARATOR exist it won't be set until settings.THOUSAND_SEPARATOR exist too - it's wrong.
Correct & simplistic code:
Also You should mark
currencyfilter asis_safe, because someone may provide currency symbol as numeric reference, like: "€".regards.
#
Thanks.
#