Explain Codes LogoExplain Codes Logo

Format numbers in Django templates

python
django-templates
number-formatting
locale-aware
Nikita BarsukovbyNikita Barsukov·Feb 7, 2025
TLDR

To rapidly format numbers in Django templates, apply floatformat for precision, a small code like {{ number|floatformat:2 }} delivers a number formatted to 2 decimal places. For comma-separation among large numbers, enable django.contrib.humanize in your INSTALLED_APPS and implement intcomma, thus: {{ number|intcomma }}. To cater for locale or currency-specific formats, write custom filters utilizing Python's locale module.

Example:

{{ number|floatformat:2 }} # 123.46 - preciseness first! {{ big_number|intcomma }} # 1,234,567 - because who doesn't love big numbers?

Setting a global formatting standard

Convenience and coherence are key in large projects. By setting USE_THOUSAND_SEPARATOR = True in your settings.py, you effect a global application of thousands separators to all numbers displayed in templates. But remember, it's done following the LANGUAGE_CODE setting's lead.

To meet global application's needs, Babel offers a customizable and locale-aware formatting solution via babel.numbers.format_number(). The world's a global village after all.

Formatted Fields in Your Model

With consistency our aim, consider providing a formatted field in your model to ensure the uniformity of number presentation across not just templates but the application as a whole.

from django.db import models from django.contrib.humanize.templatetags.humanize import intcomma class MyModel(models.Model): number = models.DecimalField(max_digits=10, decimal_places=2) formatted_number = models.CharField(max_length=20, blank=True) def save(self, *args, **kwargs): self.formatted_number = intcomma(self.number) super().save(*args, **kwargs) # Not all heroes wear capes!

Merely by using {{ my_model.formatted_number }} you can display consistently formatted numbers without the repetition of template filters. Consistency is key, isn't it?

Jazzing up with custom template tags

While humanize covers basics, certain condition scenarios demand a custom approach. Create a custom template tag in my_filters.py to gain complete control over number formatting:

from django import template import locale register = template.Library() @register.filter(name='currency') def currency(value): locale.setlocale(locale.LC_ALL, '') # All your locale are belong to us! return locale.currency(value, grouping=True)

After loading this using {% load my_filters %}, {{ price|currency }} will format numbers into currency form, cute and locale-aware.

Balancing precision and readability

With the floatformat filter, control over decimal places allows you to define precision. And remember, well-placed commas are critical for readability.

Gotchas and troubleshooting

Rounding off or locale issues might occur while formatting. Always test varying formats, especially with floating-point numbers.

And remember,

  • Humor + code = debugs faster!

The big league: Scalable and performant solutions

As projects expand, the number formatting solution must be scalable and performant, particularly with numerous data inputs.