Django Template Filter for Formating Currency

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:

  1. Add {% load humanize %} to the top of the template
  2. {{ 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 }}
Advertisements

2 thoughts on “Django Template Filter for Formating Currency

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s