When I compare the MQTT sensor value, it fails (in the template dev tool) as it is not a number.
Why and what can I do about it? Is it a bug with the MQTT sensor?
{{ (states( 'sensor.octopus_current_price' )) }}
{% if states( 'sensor.octopus_current_price' ) is number %}
a number
{% else %}
not a number
{% endif %}
any state is a string.
you need to convert them yourself.
however, if I get it right python/Jinja allows you to compare them provided they are all similar, i.e
yes, because they are not similar (different number of digits).
so string comparison is not a replacement and can only be used in cases like comparing time from sensor.time etc.
I agree that the documentation doesn’t highlight the fact that an entity’s state is a string value. The one place (that I’ve found) where it’s explained is in the State Object’s documentation and it’s easy to gloss over and underestimate its implications:
Field
Description
state.state
String representation of the current state of the entity. Example off.
We should ask baz123 if it’s natural to check there.
I know I learned that states are strings after reading many posts here and only later referred to the State Object’s documentation. It took me awhile before I realized a state with a number is actually storing it as a string. Extra confusion was the fact the Numeric State Trigger transparently converts the state to a numeric value when performing its comparison.
What isn’t natural is to see a number and think oh yes, that is a string. I doubt any amount of documentation would have triggered that without reading really carefully.
However, putting some text here might help
so make it State (as a string)
I’d have noticed that!
[edit]
A link to the docs on the States page would also help noobs I’d suggest.
well, if you write code it’s worth to pay attention to details unless you fancy constant debugging
I can tell you a short story about “see a number”:
In Developer tools → States you can see state (or attribute) of your sensor and it shows True. Then you create a template like
{{ states('sensor.test') == True }}
and it never evaluates to True, just because “True”(a string) != True (a boolean). Btu they look the same!
Another great example is attribute duration of a timer - set it to 90000 and check what States show. (Timer converts duration to its string representation so basically you can’t easily use the atribute to find out your timer’s duration if it’s more than 23h59m59s - I consider it as a bug)
All you see is an interpretation of HA’s internals.
So actually your approach
is very sensible, I do the same to make sure my templates works as expected.
could you elaborate?
And do you know that you can edit documentation yourself by clicking Edit on Github at the top right of each page?