SOLVED: Template lower then problem

Hi All,

sensor.livingroom_lux have state 11726.0

“{{ states(‘sensor.livingroom_lux’) > ‘100’ and states(‘sensor.livingroom_lux’) < ‘220’ }}”

result: TRUE

That is not correct because yes its bigger then 100 but not lower then 220

What do I not see at this simple template line?

Want replace:

  condition: numeric_state
  entity_id: sensor.livingroom_lux
  above: 100
  below: 220

to

  condition: "{{ states('sensor.livingroom_lux') > '100' and states('sensor.livingroom_lux') < '220' }}"

You are comparing strings. Try it with numbers.

"{{ 200 > states('sensor.livingroom_lux')|int > 100 }}"

To understand this line:

now its check if 200 is greater then the sensor state. and last one if sensor state is greater then 100?

Result is FALSE now

It checks if your sensor is between 100 and 200.

Thanks. Will archive this so I will never forget it

little offtopic question then

I checked other automations and this one is working
"{{ states('sensor.bathroom_humidity') < '60' }}"

change to this give same result
"{{ states('sensor.bathroom_humidity') | int < 60 }}"

What is the difference when use int?

States are strings. |int converts the string to an integer (number with no decimal part). |float converts the string to a number with a decimal fraction.

You were just lucky that when comparing strings you got the right result. This is not guaranteed unless the strings are the same length.

Put this in the template editor:

{{ '60' > '7' }}
{{ '60' > '07' }}
{{ int('60') > int('7') }}
{{ 60 > 7 }}

Funny output…

false
true
true
true

Only the first one gives a funny result. For me its logic that 60 is larger then 7
But seems that its remove the 0 then its lower then 7

It is exactly what is expected. The numbers with quotes around them are not numbers. They are strings. They are not compared the way numbers are.

More for you to try:

{{ 'foo' > 'bar' }}
{{ 'foo' > 'rab' }}

How does this work. f is higher then b but not higher then r?

thank you so much for this very clear way to explain how it work!
I will check my automations, and correct them when needed :slight_smile: !

ASCII Table

String comparisons use the character’s ASCII code.

The ASCII code for b is higher than a so 'a' > 'b' is false.

2 Likes