How do I convert a sensor into an Integer using a Template?


I have a bug in an integration where it doesn’t like a particular sensor, and says it is not an integer.

Someone else fixed that by, as they said, using a template. I have asked for detail, but no response.

Can anyone please tell me how I convert a sensor to an integer using a template?



What’s the value of your sensor in developer tools? It may be something like “unknown” or “unavailable”, in which case that’s the issue to investigate.

What’s the real problem? What integration, what sensor, and what is the error message?

You can convert a sensor state (which is always a string) to an integer in a template for doing arithmetic on it. For example:

{{ states('sensor.power_in_kilowatts')|int(0) * 1000 }}

will give you a figure in watts. If the sensor isn’t working for any reason and its state can’t be converted, the int filter will use 0 as a default.

I don’t think that’s your issue though. If an integration is expecting to see something that looks like an integer in a sensor but it isn’t seeing that, a template isn’t going to help you. Give more details.


@arganto Where do I put that? Which config file, etc?

@Stiltjack and @Troon

The integration is foxess_em. The bug has been reported by someone else, and I have also added that I have the same issue. The first person said that they had fixed it using a template.

in my home assistant log it says:

error (Main thread) [custom_components.foxess_em.battery.battery_controller] ValueError(“invalid literal for int() with base 10: ‘94.0’”)

I can tell from the value (94.0) that this is the battery State of Charge, which is another sensor that works just fine elsewhere.