2 Tamplates, same result. But which is the best/cleanest?

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

- sensor:
    - name: "Main sensor"
      unit_of_measurement: 'W'
      device_class: power
      state_class: measurement
      state: "{{ ((states('sensor.consumption_a')|float)*1000 -
                  states('sensor.consumption_b')|float)
              }}"

or

- sensors:
    main_sensor:
      friendly_name: Main sensor
      unit_of_measurement: 'W'
      value_template: >-
        {% set consumption_a = (states('sensor.consumption_a') | float * 1000) %}
        {% set consumption_b = states('sensor.consumption_b') | float %}
        {% set main_sensor = (sensor.consumption_a - sensor.consumption_b) | float %}

it’s preference.

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) }}
1 Like

About last useless float, you clarify me an additional doubt
And your code proposal is so smart!

Thank you