Login

currency filter without using locale

Author:
andzep
Posted:
February 20, 2011
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

darek (on February 21, 2011):

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:

@register.filter()
def currency(value):
    symbol = getattr(settings, 'CURRENCY_SYMBOL', '$')
    thousand_sep = getattr(settings, 'THOUSAND_SEPARATOR', ',')
    decimal_sep = getattr(settings, 'DECIMAL_SEPARATOR', '.')

    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:])

Also You should mark currency filter as is_safe, because someone may provide currency symbol as numeric reference, like: "€".

regards.

#

gp3 (on May 20, 2011):

Thanks.

#

Please login first before commenting.