Basic math?

I’m trying to create a pseudo sensor for last lightning hit distance. In the case that no daily lightning strikes have been recorded, I want the pseudo sensor to have a zero value, otherwise use the value recorded in sensor.acurite_6045m_a_10_lightning_distance. Looks like it should work, but it doesn’t. The last recorded value is always printed. What am I doing wrong?

    lightning_sd:
      friendly_name: "Lightning"
      value_template: "{{ states('sensor.lightning_d') }}"
      unit_of_measurement: "Strike(s)"
      icon_template: mdi:lightning-bolt
    lightning_sx:
      friendly_name: "Distance"
      value_template: >
        {% set strikes = states('sensor.lightning_d') | int %}
        {% set distance = states('sensor.acurite_6045m_a_10_lightning_distance') | float %}
        {% if strikes == 0 %}
          0
        {% elif distance > 0 %}
          {{ distance | round(0) }}
        {% else %}
          0
        {% endif %}
      unit_of_measurement: "mi"
      icon_template: mdi:lightning-bolt

This would be a lot easier if you ditch the legacy template sensor platform in favour of the new template integration.

Use a triggered template sensor.

Time trigger at 0:00 → reset.

Lightning trigger → update lightning distance.

Thanks for the link.