This is a consolidation of stuff on Stackoverflow. It works with Django 1.7.
The goal, format floats, with 2 decimal places and commas every three digits to the left of the decimal:
- Add {% load humanize %} to the top of the template
- {{ my_float_var|floatformat:”2″|intcomma }}
On Stackoverflow, some posts tell you to add humanize to your installed apps in settings. I suspect that sometime in the past, humanize was not part of the Django standard library. I am using Django 1.7 and it was not necessary.
Add $ Prefix
If you want to add a prefix such as $ when there is an amount, but not when the field is blank, then a custom template is the way to go. First, read the Django docs for the basics of creating custom template tags. Then make this tag:
from django import template from django.contrib.humanize.templatetags.humanize import intcomma register = template.Library() @register.filter def prepend_dollars(dollars): if dollars: dollars = round(float(dollars), 2) return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:]) else: return ''
Now in your template, put:
{{ my_float_var | prepend_dollars }}