Float with fixed number of decimals

Hi All,
I’m trying to get a fixed number of decimals in a value template.

value_template: "{{ (states('sensor.1') | float  +
                           states('sensor.2') | float        -
                           states('sensor.3') | float        -
                           states('sensor.4') | float) | round(3)
                        }}"

This works except when the last decimal is zero. Is there a way of formatting a float to get a fixed number of decimals even when the last decimal(s) round up to zero
Thx
PPee

How about…

{{ 
    "%0.1f" | format(
        (states('sensor.1') | float  +
        states('sensor.2') | float        -
        states('sensor.3') | float        -
        states('sensor.4') | float) | round(3)
    )
 }}
value_template: >
  {% set total = [states.sensor.1, states.sensor.2, states.sensor.3, states.sensor.4] 
                 | map(attribute='state') |  map('float') | sum %}
  {{ '{:.3f}'.format(total) }}

If you were to create a group containing the four sensors, the template can be reduced to:

value_template: >
  {{ '{:.3f}'.format(expand('group.mygroup') | map(attribute='state') | map('float') | sum ) }}

You can confirm it by pasting this into the Template Editor:

{{'{:.3f}'.format(0)}}

Screenshot from 2020-10-06 16-00-36

3 Likes

Hi 123Taras
Thx, that works fine!, but now I’m struggling to get the subtraction working. because the first two sensor values are added and the last two are subtracted. It is not a simple summation.
Is it possible to integrate

{{'{:.3f}'.format(0)}}

into my template and/or is there a smart way to handle the substraction
PPee

{{'{:.3f}'.format((states('sensor.1') | float  +
                   states('sensor.2') | float  -
                   states('sensor.3') | float  -
                   states('sensor.4') | float) )}}
1 Like

Thx Hellis, that worked
PPee

It wasn’t me…
@123 is the one you should thank.

The only reason his did not “work” was because he, just like me missed the subtraction.
I was surprised when I read subtraction in your post, “what subtraction!”, and I looked again.

@123 T thx :+1:

1 Like

You’re welcome and Hellis81 is right, I also glossed over the fact that it’s not a simple summation. Anyway, the key to displaying three zeros in the decimal places, even when the value is zero, is the :.3f used with the format method.

For more information:
https://www.w3schools.com/python/ref_string_format.asp

1 Like

Thx 123 Taras,
Tried to apply this also to syntax below but doesn’t work… Studied jinja2 for a solution, but no result. How would you integrate

{:.3f}

in this syntax?

- platform: mqtt
  state_topic: "Topic/Topic"
  name: 'Name'
  value_template: '{{ value_json["sensor"][0]["value"] }}'

Really appreciate your input!

I define a string containing a single placeholder

"{}"

I want that placeholder to format its received value to be displayed with three decimal places

"{:.3f}"

The placeholder is used by the string’s format method

"{:.3f}".format()

I include what I want to pass to the placeholder: value_json["sensor"][0]["value"]

"{:.3f}".format(value_json["sensor"][0]["value"])

However, the placeholder is expecting to receive a float value and I’m not sure what is produced by value_json["sensor"][0]["value"]. To be safe, I will filter it with float.

"{:.3f}".format(value_json["sensor"][0]["value"] | float)

Finally, I include it in the MQTT Sensor as a template:

- platform: mqtt
  state_topic: "Topic/Topic"
  name: 'Name'
  value_template: '{{"{:.3f}".format(value_json["sensor"][0]["value"] | float) }}'
4 Likes

Great, got it Taras, Thx for the explanation. It worked !!
PPee

1 Like

It would appear to me that this method no longer works in the same way. If the result can be parsed as a number, it will be processed as a number. The fixed decimals will only appear if the resulting string contains a character that prevents it from being turned into a number.

This change in behaviour can also be seen in the template editor: if I enter {{'{:,.3f}'.format(0)}}, I get a result type “number” and value “0”. I could understand this if it had anything to do with the unit_of_measurement of the entity (kWh in my case), but then I’d expect this to display in the same way for the non-template entities I’m using.

I’m wondering if this is a problem with the dev tools template editor…
I noticed that when the editor screen is completely blank and then you enter {{'{:.3f}'.format(0)}}, you get the results as you described.

But if there are other items in the template editor, such as the entries you get after RESET TO DEMO TEMPLATE, then when I add to these entries the following: {{'{:.3f}'.format(0)}}, this produces 0.000. Although it shows Result type: string, when I try: {{'{:.3f}'.format(0) | is_number() }} the result is True

That is somewhat to be expected, because then there’s additional output from the other statements, which turns everything into a string as a result.

I’m completely lost…
this is my string, and no matter how i try to setup the format, it either doesnt do it or makes it become unavailable, I’m trying to only have 2 decimal places.

"{{states('sensor.solaredge_current_power')| float / 1000  }}"

| float / 1000 | round(2)