Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number formatting in Django template

Tags:

python

django

I have an dictionary as follows:

{'warranty': '1 jaar', 'delivery': u'2017-06-13', 'to_pay': 9000.0, 'deposit': 1000.0}

I send it to Django template and I want to show to_pay as 9.000,00. But I can't.

I have

{% load humanize %}
{% load i18n %}
{% load l10n %}

at the top of the template and I have

USE_I18N = True
USE_L10N = True

in settings.py

What have I tried:

{{ car.sale.to_pay|floatformat:2|intcomma }} // 9,000,00
{{ car.sale.to_pay|intcomma }} // 9.000,0  almost good, but I need two zeroes after comma
{{ car.sale.to_pay|localize }} // 9000,0

Any idea?

like image 392
Boky Avatar asked Jun 13 '17 14:06

Boky


1 Answers

Custom Template Filter

You can always create your own template filter to get the desired result. Here's an implementation that uses intcomma to format the number to your desired result

from django import template
from django.contrib.humanize.templatetags.humanize import intcomma

register = template.Library()

@register.filter
def my_float_format(number, decimal_places=2, decimal=','):
    result = intcomma(number)
    result += decimal if decimal not in result else ''
    while len(result.split(decimal)[1]) != decimal_places:
        result += '0'
    return result

Then to use in a template

{% load my_tags %}
{{ 450000.0|my_float_format }}

Renders this

450.000,00

Old Answer (Incorrect)

You can use the stringformat filter to use basic python string formatting first and get the desired number of decimal places, then pass it through intcomma to get the number formatting.

{% load humanize %}

{{ car.sale.to_pay|stringformat:'0.2f'|intcomma }}
like image 186
Brobin Avatar answered Oct 17 '22 08:10

Brobin