Format numbers in django templates
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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:
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:
Understand floatformat Behavior
floatformat has a few modes worth knowing:
- Positive
nforces exactlyndecimals. - Negative
ntrims trailing zeros up tonplaces. - No argument uses default behavior that may hide decimals for integers.
Examples:
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.
In templates, localize can control formatting scope:
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:
Template example:
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.
Then in template:
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.humanizebefore usingintcomma. - 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
- Format timedelta to string
- Formatting floats without trailing zeros
- Formatting yesterday's date in python
- Frequency counts for unique values in a NumPy array
- from ... import vs import .
- From conda create requirements.txt for pip3
- from kafka import KafkaClient ImportError No module named kafka
- from keras.backend.tensorflow_backend import set_session
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.