Formatting floats with decimal dots and limited decimal part in Django templates

gerosalesc picture gerosalesc · Dec 11, 2015 · Viewed 16k times · Source

I know I can limit the number of decimals in a float by using the filter floatformat:2 which output a localized float and also I know the filter stringformat:"f" which outputs a dotted float like 1.54 instead of a localized comma float like 1,54.

For instance, if the original float is 1.54233 I would like to print 1.54 and not 1,54 or 1.54233. Can this be achieved without the need of a custom filter?

Answer

maazza picture maazza · Dec 11, 2015

just use the localize/unlocalize format separator

https://docs.djangoproject.com/en/1.9/topics/i18n/formatting/#std:templatefilter-localize

For example:

{% load l10n %}

{{ value|localize }}

To disable localization on a single value, use unlocalize. To control localization over a large section of a template, use the localize template tag. unlocalize¶

Forces a single value to be printed without localization.

For example:

{% load l10n %}

{{ value|unlocalize }}

To force localization of a single value, use localize. To control localization over a large section of a template, use the localize template tag.

edit:

see https://docs.djangoproject.com/en/1.9/topics/i18n/translation/#switching-language-in-templates

{% load i18n %}

{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<p>{% trans "Welcome to our page" %}</p>

{% language 'en' %}
    {% get_current_language as LANGUAGE_CODE %}
    <!-- Current language: {{ LANGUAGE_CODE }} -->
    <p>{% trans "Welcome to our page" %}</p>
{% endlanguage %}

you can switch languages to force the display if localize/unlocalize does not work