format_thousands

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import re
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@stringfilter
def format_thousands(val):
    '''
    Format a number so that it's thousands are separated by commas. 
    
    1000000 > '1,000,000'
    10000 > '10,000'
    1000.00 > '10,000.00'
    '''
    return ','.join(re.findall('((?:\d+\.)?\d{1,3})', val[::-1]))[::-1]

register.filter('format_thousands', format_thousands)

More like this

  1. Converts an integer or floating-point number or a string to a string containing the delimiter character (default comma) after every delimeter_count digits (by default 3 digits) by pikhovkin 1 year, 2 months ago
  2. fast non-locale aware float format by percivall 3 months, 3 weeks ago
  3. (en-US) Humanized Decimal Field by ActionScripted 4 years, 10 months ago
  4. Newforms field for decimals with a comma by jonasvp 5 years, 2 months ago
  5. Quantize decimal template filter by bl4th3rsk1t3 4 years ago

Comments

danny_adair (on June 28, 2011):

https://docs.djangoproject.com/en/dev/ref/contrib/humanize/#intcomma

#

cootetom (on June 29, 2011):

Oh had I of found it in humanize I'd not have bothered. I forgot that library existed! Still, it's nice to see a few different solutions to the same problem just for interests sake.

#

percivall (on January 26, 2013):

Also, with modern Python versions: "{:,}".format(val)

#

(Forgotten your password?)