Template solution range

I want to calcualte a template that lies within 0 - 100 range. I have done it as follows:

{% set position = states('sensor.sun_elevation')|float / 60 * 100 %}
{% if position < 0 %}
  {{ 0 }}
{% elif position > 100 %}
  {{ 100  }}
{% else %}
  {{ position }}
{% endif %}

But I feel its kind of verbose. Is there a function that I am missing?

Ben

{{ min(100,max(0,states('sensor.sun_elevation')|float/60*100)) }}

Another way:

{{ ([0, 100 * states('sensor.sun_elevation')|float(0) / 60), 100]|sort)[1] }}

This sorts the list in increasing order and picks the middle value.

e.g.

[0,-42,100] β†’ [-42,0,100] β†’ 0

[0,42,100] β†’ [0,42,100] β†’ 42

[0,142,100] β†’ [0,100,142] β†’ 100

2 Likes

That is so elegant :heart_eyes:

Taras (123) taught me that one.

There’s a surprise :rofl:

1 Like