This snippet is a combination of the existing currency snippets I found and some modifications to use your own settings without the need to have the locale installed on the system.
You can define in settings.py:
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '.'
CURRENCY_SYMBOL = u'€'
With the above settings, using {{ 1234.30|currency }}
on a template would result in €1.234,30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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:])
|
More like this
- Browser-native date input field by kytta 1 month, 1 week ago
- Generate and render HTML Table by LLyaudet 1 month, 2 weeks ago
- My firs Snippets by GutemaG 1 month, 3 weeks ago
- FileField having auto upload_to path by junaidmgithub 2 months, 4 weeks ago
- LazyPrimaryKeyRelatedField by LLyaudet 3 months, 1 week ago
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
currency
filter asis_safe
, because someone may provide currency symbol as numeric reference, like: "€".regards.
#
Thanks.
#
Please login first before commenting.