The Python Oracle

Format numbers in django templates

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Question
00:31 Accepted answer (Score 404)
00:54 Answer 2 (Score 130)
01:14 Answer 3 (Score 66)
01:50 Answer 4 (Score 35)
02:20 Thank you

--

Full question
https://stackoverflow.com/questions/3464...

Accepted answer links:
[humanize]: http://docs.djangoproject.com/en/dev/ref...

Answer 2 links:
[floatformat]: https://docs.djangoproject.com/en/stable...
[intcomma]: https://docs.djangoproject.com/en/stable...

Answer 4 links:
[documentation]: https://docs.djangoproject.com/en/stable...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django

#avk47



ACCEPTED ANSWER

Score 418


Django's contributed humanize application does this:

{% load humanize %}
{{ my_num|intcomma }}

Be sure to add 'django.contrib.humanize' to your INSTALLED_APPS list in the settings.py file.




ANSWER 2

Score 136


Building on other answers, to extend this to floats, you can do:

{% load humanize %}
{{ floatvalue|floatformat:2|intcomma }}

Documentation: floatformat, intcomma.




ANSWER 3

Score 67


Regarding Ned Batchelder's solution, here it is with 2 decimal points and a dollar sign. This goes somewhere like my_app/templatetags/my_filters.py

from django import template
from django.contrib.humanize.templatetags.humanize import intcomma

register = template.Library()

def currency(dollars):
    dollars = round(float(dollars), 2)
    return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])

register.filter('currency', currency)

Then you can

{% load my_filters %}
{{my_dollars | currency}}



ANSWER 4

Score 11


If you don't want to get involved with locales here is a function that formats numbers:

def int_format(value, decimal_points=3, seperator=u'.'):
    value = str(value)
    if len(value) <= decimal_points:
        return value
    # say here we have value = '12345' and the default params above
    parts = []
    while value:
        parts.append(value[-decimal_points:])
        value = value[:-decimal_points]
    # now we should have parts = ['345', '12']
    parts.reverse()
    # and the return value should be u'12.345'
    return seperator.join(parts)

Creating a custom template filter from this function is trivial.