Login

currency filter with minus symbol replacement and css class adding

Author:
sspross
Posted:
January 17, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

uses the system or specified locale to format a number. a css class called 'negative' would be added if the format is negative and the minus symbol would be replaced if it is the last char.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django import template

register = template.Library()
 
@register.filter()
def currency(value, grouping=True):
    """
    e.g.
    import locale
    locale.setlocale(locale.LC_ALL, 'de_CH.UTF-8')
    currency(123456.789)  # Fr. 123'456.79
    currency(-123456.789) # <span class="negative">Fr. -123'456.79</span>
    """
    result = locale.currency(value, grouping=grouping)
    
    # add css class if value is negative
    if value < 0:
        # replace the minus symbol if needed
        if result[-1] == '-':
            length = len(locale.nl_langinfo(locale.CRNCYSTR))
            result = '%s-%s' % (result[0:length], result[length:-1])
        return '<span class="negative">%s</span>' % result
        
    return result

More like this

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

Comments

Please login first before commenting.