I’ve reached the same result using 2 different ways.
It’s a simple sensor generated from the difference of 2 others.
I just wonder which is the best or cleanest one. Or if one of them is simply the wrong way
Just keep in mind that if you have 2 floats and you add them, you don’t need to say the result is also a float. Meaning the float in this line is doing nothing:
Also, personally, I like to build in startup safety and order of operations in math is always applied. So I avoid using unnecessary parenthesis. It would look like this:
- sensors:
main_sensor:
friendly_name: Main sensor
unit_of_measurement: 'W'
value_template: >-
{% set a = states('sensor.consumption_a') | float(none) %}
{% set b = states('sensor.consumption_b') | float(none) %}
{{ a * 1000 - b if a | is_number and b | is_number else none }}
or
- sensors:
main_sensor:
friendly_name: Main sensor
unit_of_measurement: 'W'
value_template: >-
{% set a = states('sensor.consumption_a') | float(none) %}
{% set b = states('sensor.consumption_b') | float(none) %}
{{ (a | is_number and b | is_number) | iff(a * 1000 - b, none) }}