Custom template sensor becomes unavailble when dividing by zero

I have this sensor set up in my configuration.yml file:

# Calculates some values
template:
  - sensor:
      - name: "Daily COP hot water energy"
        state: "{{ (states('sensor.hp_dailyhotwaterenergyproduced')|float / states('sensor.hp_dailyhotwaterenergyconsumed') |float ) |round(2) }}"
        unit_of_measurement: COP

The problem is that sometimes the sensor value here can be 0 and thus as division by 0 is not possible, the sensor shown in my card in my dashboard shows unavailable.

Would it be possible to do something here so that the value becomes simply 0 instead for example? :slight_smile:

# Calculates some values
template:
  - sensor:
      - name: "Daily COP hot water energy"
        state: >
          {% set produced = states('sensor.hp_dailyhotwaterenergyproduced') | float(0) %}
          {% set consumed = states('sensor.hp_dailyhotwaterenergyconsumed') | float(0) %}
          {{ (produced / consumed) | round(2) if consumed > 0 else 0 }}
        unit_of_measurement: COP

Awesome, thanks!

1 Like