Numerical formats from json

I am getting results from a json rest service with numbers in the format of:

1,005.050 kWh

So a “,” as thousands separator and a ‘’." as decimal separator. But for calculations, I need to have the opposite way!

If I check the template with:

{% set x = '1,005.050 kWh' %}
{{ x.split(' ')[0].replace('.', ',').replace(',', '') | float }}
{{ x.split(' ')[0].replace(',', '').replace('.', ',') | float }}

I get:

1005050.0
0

So, the replace functions are evaluated from right to left? Or is there an easier way to convert numbers from US notation to EU notation?

No, they are evaluated from left to right. At the end of each line you convert the value to a float. That explains why the second line evaluates to 0 (1,005.050 → 1005.050 → 1005,050 → not a float → default to 0).

I think what you want is:

{% set x = '1,005.050 kWh' %}
{{ x.split(' ')[0].replace(',', '') | float }}
2 Likes

Thnx for the explanation!