Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number format localized in Django?

hope simple question gets an simple answer. I'd just like to compose Django's filters so I get formated floating point number locale-aware:

{{123.45|floatformat:1}}
"123.5"  <= correct
{{123.45|localize}}
"123,45"  <= correct, in my locales decimal separator is a comma
{{123.45|floatformat:1|localize}}
"123.5"  <= wrong, point instead of comma. Expected output: "123,5"

How can I apply both filters at the same time ?

Thanks.

like image 482
David Unric Avatar asked Nov 11 '12 21:11

David Unric


People also ask

What are localized fields in Django?

django-localized-fields is an implementation of a field class for Django models that allows the field's value to be set in multiple languages. It does this by utilizing the hstore type (PostgreSQL specific), which is available as models.

What is use_ l10n in Django?

When it's enabled, two users accessing the same content may see dates, times and numbers formatted in different ways, depending on the formats for their current locale. The formatting system is disabled by default. To enable it, it's necessary to set USE_L10N = True in your settings file.

What is the format of datetime in Django?

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' .

What are templates in Django?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


1 Answers

Django's floatformat filter returns a string, not actually a float number, so when you pass that value to localize, you are passing a string, not a number (int, float, etc) and therefore just returns the given string.

To achieve what you want, you can't combine these two filters in Django, since both return a string. To do that, you would have to make your own filter which will do the behavior you want. To make things easier, you can always start with the code in the default filters and modify that to your specification. floatformat code is here and localize is here.

like image 197
miki725 Avatar answered Sep 20 '22 13:09

miki725