Template for unavailable state

Hi, I have three temperature sensors, one of which (not always the same one) occasionally shows an unavailable state. To get around this, I created a template that averages between the three, if all are available, or between two of them if the third is unavailable. But it doesn’t work when an unavailable statue occurs and I can’t figure out what’s wrong. The template is the following:

{% if states('sensor.estacion_meteorologica_esphome_temperatura') != unavailable %}
    {% if states('sensor.estacion_meteorologica_sonoff_temperature') != unavailable %}
        {% if states('sensor.temperatura_en_dos_hermanas_montecillos') != unavailable %}
            {{ "%.2f" | format(((states('sensor.estacion_meteorologica_esphome_temperatura')|float + 
            states('sensor.estacion_meteorologica_sonoff_temperature')|float+
            states('sensor.temperatura_en_dos_hermanas_montecillos')|float) /3 - 0.5) | round (1)) }}
        {% else %}
            {{ "%.2f" | format(((states('sensor.estacion_meteorologica_esphome_temperatura')|float + 
            states('sensor.estacion_meteorologica_sonoff_temperature')|float) /2 - 0.5) | round (1)) }}
        {% endif%}
    {% else %}
        {{ "%.2f" | format(((states('sensor.estacion_meteorologica_esphome_temperatura')|float + 
        states('sensor.temperatura_en_dos_hermanas_montecillos')|float) /2 - 0.5) | round (1)) }}
    {% endif%}
{% else %}
    {{ "%.2f" | format(((states('sensor.estacion_meteorologica_sonoff_temperature')|float+
    states('sensor.temperatura_en_dos_hermanas_montecillos')|float) /2 - 0.5) | round (1)) }}
{% endif%}

I really appreciate any help

There is an average sensor helper that does this for you. Despite the name, it also,averages:

1 Like

Thanks, does that sensor also manage unavailable states?

Yes. If it does not know the state, it ignores it for the result.

Oh, thank you so much, if only I had known that before!
Do you know how I can mark yours as the correct answer? This is the first time I’ve created a topic…
Regards!