Search code examples
htmlcssdjangotemplatesdecimal

Decimal numbers with fraction part in Django template for css purposes


I have a django template where I want to calculate values and then use them in css. It looks like:

padding-top: {{ VAL1|divide:VAL2|multiply:VAL3 }}px

It calculates the value I need albeit in some strange fashion via filters. The problem is that the result of calculation is a decimal number with fractional part and comma as separator, like 12,34. Whereas 12.34 is actually needed for css to work properly - padding-top: 12,34px isn't valid css due to the comma. I tried to use floatformat filter - no success. It looks like a simple thing but I cannot wrap my head around it.


Solution

  • After delving into django docs I learnt that the described effect may occur due to the localization, so I added the following in the template:

    {% load l10n %} # at the beginning
    ...
    {{ VAL1|divide:VAL2|multiply:VAL3|unlocalize }} # to output without localization
    

    Seems it helped, although I don't mind if someone savvy brings another solution.