currency filter without using locale

 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. Currency filter by kljensen 6 years, 3 months ago
  2. currency filter with minus symbol replacement and css class adding by sspross 3 years, 3 months ago
  3. Currency Object by Rupe 4 years, 10 months ago
  4. Currency Widget by Rupe 4 years, 10 months ago
  5. Currency Form Field by Rupe 4 years, 10 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: "&#8364".

regards.

#

gp3 (on May 20, 2011):

Thanks.

#

(Forgotten your password?)