Login

Currency formatting filter

Author:
rafa
Posted:
December 4, 2009
Language:
Python
Version:
1.1
Tags:
template filter currency formatting
Score:
1 (after 1 ratings)

See the function docstring for usage.

This template filter has a couple of drawbacks:

  • Uses locale.setlocale which, according to the Python docs, is not thread safe. I don't know how this may affect Django applications.

  • Requires Python 2.5+.

Updated 2011-03-16.

 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import locale

from django.template import Library

register = Library()

@register.filter
def currency(value, arg = '', symbol = True):
    '''
    Currency formatting template filter.

    Takes a number -- integer, float, decimal -- and formats it according to
    the locale specified as the template tag argument (arg). Examples:

      * {{ value|currency }}
      * {{ value|currency:"en_US" }}
      * {{ value|currency:"pt_BR" }}
      * {{ value|currency:"pt_BR.UTF8" }}

    If the argument is omitted, the default system locale will be used.

    The third parameter, symbol, controls whether the currency symbol will be
    printed or not. Defaults to true.

    As advised by the Django documentation, this template won't raise
    exceptions caused by wrong types or invalid locale arguments. It will
    return an empty string instead.

    Be aware that currency formatting is not possible using the 'C' locale.
    This function will fall back to 'en_US.UTF8' in this case.
    '''

    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)

More like this

  1. Currency filter by kljensen 7 years, 7 months ago
  2. A simple rest template filter by marinho 7 years, 9 months ago
  3. Template filters utils by marinho 7 years, 9 months ago
  4. Convert numbers in USA notation to brazilian notation by eOliva 6 years, 11 months ago
  5. Date/time util template filters by marinho 7 years, 9 months ago

Comments

Please login first before commenting.