Wanting to simplify a template setting max numeric value for a variable

I'm wondering if there is a way to simplify the template yaml below?
I have a pressure sensor in a water tank. It provides a voltage, sensor.tankd_adc, from which I calculate water depth (and from that, I calculate %full & volume).
This template works (it's in a template.yaml file) but is there a way to use iif?

   - sensor:
    - name: hTankD
      unit_of_measurement: "m"
      device_class: distance
      unique_id: 10240032
      state: >
        {% set Vi = states('sensor.tankd_adc') | float(default=0) %}
        {% if Vi > 5.81 %}
          {% set Vi = 5.81 %}
        {% endif %}
        {{ (Vi * 0.30981 + 0.06) | round(3) }}
- sensor:
    - name: hTankD
      unit_of_measurement: "m"
      device_class: distance
      unique_id: 10240032
      state: >
        {% set Vi = [states('sensor.tankd_adc') | float(0), 5.81] | min %}
        {{ (Vi * 0.30981 + 0.06) | round(3) }}

If your sensor value is above 5.81 then the min (minimum) filter selects 5.81. If your sensor value is below 5.81 then the minimum filter selects that value.

Aaah, lovely. Thank you. Thought there must be something - very neat.

Even briefer, clipping the output of the calculation:

state: "{{ min(1.86, states('sensor.tankd_adc')|float(0)*0.30981+0.06)|round(3) }}"

1.86 is the result of the calculation with 5.81 as the input. That might be more readable for you in future if you recognise 1.86m as a physical tank dimension more than you recognise 5.81V as the ADC output.

1 Like

Thanks @Troon.

Interesting, not a structure I've seen before (although that's not saying much!). I would have been trying to put brackets around the whole line.