django
templates
number formatting
web development
python

Format numbers in django templates

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Django templates include built in filters for displaying numbers cleanly without moving all presentation logic into views. The tricky part is deciding which formatting rule belongs in the template layer and which belongs in Python code before rendering. A reliable strategy keeps output consistent across pages, locales, and reporting screens without turning templates into mini calculators.

Use Built In Filters First

Django already ships common formatting tools, so start there before writing custom template filters.

Typical examples:

django
1{% load humanize %}
2
3{{ amount|intcomma }}
4{{ amount|floatformat:2 }}
5{{ ratio|floatformat:1 }}%

intcomma inserts grouping separators and floatformat controls decimal places. This is enough for many dashboard and reporting views.

To use intcomma, ensure humanize is enabled in settings:

python
1INSTALLED_APPS = [
2    # ...
3    "django.contrib.humanize",
4]

Understand floatformat Behavior

floatformat has a few modes worth knowing:

  • Positive n forces exactly n decimals.
  • Negative n trims trailing zeros up to n places.
  • No argument uses default behavior that may hide decimals for integers.

Examples:

django
{{ value|floatformat:2 }}
{{ value|floatformat:-2 }}
{{ value|floatformat }}

Use one style consistently across a product area. Mixed precision rules can confuse users when numbers appear side by side.

Apply Localization Correctly

If your app serves multiple locales, localization settings affect separators and decimal symbols. Keep locale settings explicit and test templates under target languages.

python
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = "en"

In templates, localize can control formatting scope:

django
1{% load l10n %}
2{% localize on %}
3  {{ amount }}
4{% endlocalize %}

If a specific value must always use machine style numeric output, disable localization locally.

Localization matters most when the same raw value can appear in both human and machine facing contexts. A download button might require plain 1234.56, while a dashboard card for the same value should show a locale aware separator pattern. Keeping that distinction explicit avoids subtle bugs when users copy values between systems.

Keep Business Logic Out of Templates

Templates should format values, not calculate them. Compute totals, tax, and conversion in Python code, then pass final numbers for display.

View example:

python
1from decimal import Decimal
2from django.shortcuts import render
3
4
5def invoice_view(request):
6    subtotal = Decimal("1299.90")
7    tax = subtotal * Decimal("0.13")
8    total = subtotal + tax
9    return render(request, "invoice.html", {
10        "subtotal": subtotal,
11        "tax": tax,
12        "total": total,
13    })

Template example:

django
1{% load humanize %}
2Subtotal: {{ subtotal|floatformat:2|intcomma }}
3Tax: {{ tax|floatformat:2|intcomma }}
4Total: {{ total|floatformat:2|intcomma }}

This separation keeps templates readable and testable.

Create a Custom Filter Only for Reusable Rules

If your app requires a repeated display convention such as accounting style currency, create a custom filter with narrow responsibility.

python
1from decimal import Decimal, InvalidOperation
2from django import template
3
4register = template.Library()
5
6
7@register.filter
8def money(value):
9    try:
10        amount = Decimal(value)
11    except (InvalidOperation, TypeError):
12        return "-"
13    return f"${amount:,.2f}"

Then in template:

django
{% load money_filters %}
{{ total|money }}

Write tests for custom filters so edge cases remain stable.

This is also the right place to enforce domain specific rules such as showing negative numbers in parentheses or returning a placeholder for missing values. Put those rules in one filter instead of scattering conditional branches throughout templates.

Test Rendering, Not Only Python Functions

Formatting bugs often surface only in template output. Add template rendering tests for:

  • Small integers.
  • Large values.
  • Negative values.
  • Null like values.
  • Locale changes.

A tiny rendering test catches many production display regressions.

Keep a Clear Display Policy

Number formatting should follow a project level policy, not individual developer preference. Define one style for decimals, thousand separators, and negative values in product documentation. Then map that policy to template filters and custom tags.

For example, if finance pages always need two decimals and commas, enforce that in shared template snippets instead of repeating ad hoc formatting in many files. Consistent display rules reduce support tickets and prevent user confusion when values appear in tables, charts, and exports.

Common Pitfalls

  • Doing arithmetic in templates instead of views or services.
  • Mixing incompatible numeric formats across pages.
  • Forgetting to enable django.contrib.humanize before using intcomma.
  • Assuming one locale format is correct for all users.
  • Creating custom filters when built in filters already solve the problem.

Summary

  • Use Django built in numeric filters before introducing custom formatting code.
  • Keep calculations in Python and keep templates focused on presentation.
  • Apply localization intentionally and test with real locale settings.
  • Standardize decimal precision and separator conventions per product area.
  • Add template rendering tests for numeric edge cases and locale behavior.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.