Card is flickering to unavailable due to unknown state of sensor

Hi,
I deployed a ESPhome device that measures the distance inside a water tank via sonar. The distance is queried multiple times per second and sometimes the value is reported as unknown which causes my gauge card to flicker in and out.
Is there a way to prevent this? All my attempts in catching only numeric values so far did not work. Here is my template so far:

- name: "WTL Sensor 01 nan handled"
  unique_id: wtl_01_safe
  unit_of_measurement: "%"
  state: >
    {% set val = states('sensor.water_tank_level_sensor_01_distance') | float(default=nan) %}
    {% if val == val %}
      {{ ( (1.71 - val) / (1.71 - 0.33) * 100 ) | round(1) }}
    {% else %}
      -999
    {% endif %}
  availability: >
    {{ states('sensor.water_tank_level_sensor_01_distance') not in ['unknown', 'unavailable', 'None'] }}

Thanks in advance!

I really suck at templating, but what happens if you change float(default=nan) to float(default=0)?

Thanks for the suggestion, but unfortunately this does not change anything. The value of the template still shows unknown every other second and the card is disappearing.
I also tried to use filter templates, but it seems as soon as the sensor value sensor.water_tank_level_sensor_01_distance becomes unknown, every operation on it also yields unknown.
This seems like a trivial problem that others should have encountered as well though. :thinking: