Sergey
Sergey

Reputation: 341

Django templates: output float with all decimal places

how can I output this number in django templates (number of decimal places is variable and I don't know it in advance):

x = 0.000015

1)

{{x}}

output is:

1,5e-05

2)

{{x|stringformat:"f"}}

output is:

0.000015

which is not localized, there should be comma! I need output to be localized and keep all decimal places.

I can't believe that django can't handle such a simple task using built-in tools.

UPDATE: I have correct settings already:

LANGUAGE_CODE = 'ru'
USE_L10N = True

And default Django output works fine for most of float numbers, it only fails on this small number. It outputs with exponent notation, but I need to output as float with all decimal places (number of decimal places is variable).

Upvotes: 4

Views: 7033

Answers (3)

Sergey
Sergey

Reputation: 341

I found an alternative solution, which works perfectly fine.

First convert FloatField to DecimalField:

some_value = models.DecimalField(max_digits=20, decimal_places=15)

and then output in template as follows:

{{x.some_value.normalize}}

As result it outputs 0.000015 as "0.000015"

Upvotes: 0

neverwalkaloner
neverwalkaloner

Reputation: 47374

If you know length of numbers you can try to use floatformat filter:

{{ x|floatformat:6 }}

where 6 is length of decimal part.

Upvotes: 4

Adriano Martins
Adriano Martins

Reputation: 1808

That happens due to the wrong locale settings.
Django localization works using the the current locale settings(Format Localization):

When using Django's formatting system, dates and numbers on templates will be displayed using the format specified for the current locale.

To fix it, you should set the correct locale, I'm assuming it is pt_BR (due to the comma), but you may use it whatever locale it is correct.

try to add this on your settings:

LANGUAGE_CODE = 'pt-BR'
USE_L10N = True

and then re-run your code

Upvotes: 0

Related Questions