Template filter to format a number so that it's thousands are separated by commas.
{{ number|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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
https://docs.djangoproject.com/en/dev/ref/contrib/humanize/#intcomma
#
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.
#
Also, with modern Python versions:
"{:,}".format(val)
#
Please login first before commenting.