[Django]-How to disable formatting for FloatField in template for Django

66👍

{{ float_var|stringformat:"f" }}
👤Stef

29👍

You can now force the value to be printed without localization.

{% load l10n %}

{{ value|unlocalize }}

Taken from https://docs.djangoproject.com/en/2.2/topics/i18n/formatting/#std:templatefilter-unlocalize

14👍

I have a problem rendering lat and lng values.
My solution was:

{{ value|safe }}

5👍

You need to create a custom template filter.

from django.template import Library
from django.utils.numberformat import format

register = Library()

@register.filter
def floatdot(value, decimal_pos=4):
    return format(value, ".", decimal_pos)

floatdot.is_safe = True

Usage:

{{ float_var|floatdot }} or {{ float_var|floatdot:2 }}

2👍

You could use a custom formats.py (see “Creating custom format files” in the Django docs) and define THOUSAND_SEPARATOR and DECIMAL_SEPARATOR

THOUSAND_SEPARATOR = ''
DECIMAL_SEPARATOR = '.'

This is a global setting, so it will affect all floats displayed on your site. And you’ll have to turn on localization (USE_L10N in your settings.py).

If you have control over the template, you could simply remove the floatformat filter.

edit: I’m not sure, but perhaps you are a victim of this Django bug: #13617. Try to turn off localization support in your settings.py and see if the erroneous commas disappear:

USE_L10N = False

If that is the case, have a look at the various workarounds mentioned in the bugreport (the simplest being to turn localization off if you don’t need it anyway).

2👍

I’ve got the same issue, and as piquadrat says, it’s an annoying bug related to localization support. Changing USE_L10N = True to False solve this, it is suppposed to be fix in Django 1.3.

0👍

When print some variable for javascrip, its better to jsonify it. Write a jsonify template tag then use

{{value|jsonify}}

Template tags

from django.core.serializers import serialize
from django.db.models.query import QuerySet
import json
from django.template import Library

register = Library()

def jsonify(object):
    if isinstance(object, QuerySet):
        return serialize('json', object)
    return json.dumps(object)

register.filter('jsonify', jsonify)
👤James

Leave a comment