Format numbers in django templates


Question

I'm trying to format numbers. Examples:

1     => 1
12    => 12
123   => 123
1234  => 1,234
12345 => 12,345

It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.

Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.

1
139
11/6/2009 7:43:30 PM

Accepted Answer

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.

270
5/18/2014 12:42:15 PM

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon