Make a string sensor using template as numeric sensor

Hello,

I have a Switch Sensor that deliveres the current consumption. But after the last Home Assistant Update the value is a string, not a numeric anymore.

So I decided to create a template sensor to cast the value to float:

    pool_verbrauch_watts:
        friendly_name_template: "Pool Verbrauch (Watt)"
        value_template: "{{ states('sensor.meerschweinchen_current_consumption') | float }}"
        unique_id: "pool_verbrauch_watts"

If I test the new sensor using the template function in developer tools, I get this Messages:
{{states(‘sensor.pool_verbrauch_watts’)}}
→ 5.5

{{states(‘sensor.pool_verbrauch_watts’) | float > 5 }}
→ True

{{states(‘sensor.pool_verbrauch_watts’) > 5 }}
→ TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

Can someone tell me, what’s wrong with the template sensor?

Best regards!

A state is always a string.

Thank you. What do you recommend?

The Problem is, that a numeric trigger of an Auto script does not work - also with the new template sensor.

You have to specify a unit_of_measurement in your template sensor’s configuration.

I’m not sure what you mean here.

could you post an example of what you tried that doesn’t work?

I’m using now a switch template sensor with value_template checking for the desired value. That is working for me.

Would you please so kind and share your solution code with us?

1 Like

Definitely worth seeing what was allegedly done to circumvent this:

{{states('sensor.pool_verbrauch_watts') > 5 }}
→ TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

Because that’s a perfectly normal error message due to a mistake in the template (comparing mixed value types). Like francisp said, all state values are strings so if you want to compare it to a numeric value you have to convert it to int or float.