Help with this Template Sensor and new HA Version 2021.12

Hello to everyone could someone help me with this template sensor:

#Energia Immessa in WATT
      energia_immessa_w_attuale:
        value_template: >
          {% if states('sensor.fotovoltaico_solar_current_power') | float > states('sensor.shellyem_f4cfa2e45ce7_channel_1_power') | float -%}
              {{ states('sensor.fotovoltaico_solar_current_power') | float - states('sensor.shellyem_f4cfa2e45ce7_channel_1_power') | float }}
          {%- else -%}
            0
          {%- endif %}
        unit_of_measurement: W
        device_class: energy
        friendly_name: Energia Immessa W Attuale

I have this error sometimes when the solar panel goes offline:

Template warning: 'float' got invalid input 'unavailable' when rendering template '{% if states('sensor.fotovoltaico_solar_current_power') | float > states('sensor.shellyem_f4cfa2e45ce7_channel_1_power') | float -%} {{ states('sensor.fotovoltaico_solar_current_power') | float - states('sensor.shellyem_f4cfa2e45ce7_channel_1_power') | float }} {%- else -%} 0 {%- endif %}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2021.12

Could i put some if or something else?
I have used this template for calculate the power that i put to the grid.
Thanks a lot
Stefano

need to read

need to add default to the float

float(default=0)

2 Likes

Just replace | float with | float(0) everywhere.

3 Likes

Thanks to both

What is the difference between float(0) and float(default=0)?

Hi, just update HA to 2021.10.6.
I have several “float” in my configuration.yaml.
Can I use the replace command to replace them all with float(0) ?

Yes you can

1 Like

Using the float(0) filter will avoid the warning you saw, but it isn’t necessarily always the right thing to do. Think, for example, whether you have any automation that triggers off of this sensor, and whether or not the automation would trigger if that float value is zero.

Another approach is to use is_number() in your value template. For example, I have one like this:

        value_template: >-
          {%- if is_number(states('sensor.hallway_temperature')) -%}
            {{ states('sensor.hallway_temperature') | float | round(1) }}°
          {%- else -%}
            unavailable
          {%- endif -%}
9 Likes

Certainly the best reply at now. It is sometime preferable to set the value to unavailable instead of setting a default 0.