In Django web development, we often need to display numbers in a formatted manner for a better user experience. Django provides several built-in template filters using which we can format currency, percentages or decimal numbers.

Using Django templates’ built-in filters, we can format numbers directly within the template code without modifying the underlying Python code.

Here are a few commonly used django filters:

floatformat: The floatformat filter allows us to round a floating-point number to a specified number of decimal places.

{{ number|floatformat:2 }}

intcomma: The intcomma filter adds commas to an integer or a string representing an integer, making it more readable.

{{ number|intcomma }}

filesizeformat: The filesizeformat filter formats a number representing a file size (in bytes) into a human-readable format.

{{ filesize|filesizeformat }}

percent: The percent filter formats a decimal number as a percentage.

{{ decimal|percent }}

Following is an example of using the above Django filters.

Assume, we have a Django view which passes a variable called price to a template. The value of the price is 1250.75 and we want to format it with two decimal places and add a currency symbol and include commas for thousands.

In the Django view (views.py), pass the price variable to the template context as shown below:

from django.shortcuts import render

def my_view(request):
    price = 1250.75
    context = {'price': price}
    return render(request, 'my_template.html', context)

Now, In the template (my_template.html), use the floatformat, intcomma, and currency filters to format the price variable as shown below:

<p>Formatted Price: {{ price|floatformat:2|intcomma|currency:"USD" }}</p>

Categorized in:

Tagged in: