Templates - converting string to float unless string is 'unavailable'

In my configuration I create a new sensor based on the value of an existing sensor. In this case I don’t change it, it’s so the sensor name stays the same so I don’t need to change my automations if I change weather provider. It generally works, but sometimes Open Weather Map returns “unavailable” or some other string instead of a temperature such as “15.12”.

Here’s my sensor

      - name: Temperature Forecast Minimum
        unique_id: temperature_forecast_min
        state: "{{ states('sensor.openweathermap_forecast_temperature_low') }}"
        unit_of_measurement: "°C"

Here’s the error message

ValueError: Sensor sensor.owm_outside_humidity_current has device class 'None', state class 'None' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric >
2023-11-01 07:39:05.092 ERROR (MainThread) [homeassistant.helpers.event] Error while dispatching event for sensor.openweathermap_forecast_temperature to <Job track state_changed event {'sensor.openweathermap_for>
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 593, in state
    numerical_value = float(value)  # type:ignore[arg-type]
                      ^^^^^^^^^^^^
ValueError: could not convert string to float: 'unavailable'

I’ve been playing around in the template area with things like {% if states('sensor.openweathermap_temperature') is number %} , but sensor.openweathermap_temperature is a string rather than a number. This would be trivial in Python but I can’t work it out in Jinga2 syntax. Can anyone help?

The logic I’m after is something like this

if (sensor.openweathermap_temperature can be converted to float) then
    temperature_forecast_min = sensor.openweathermap_temperature | float
else
    temperature_forecast_min = 0

Add a default to your floatfloat(0)

3 Likes

Ah, that’s pretty easy, thanks Drew. I’ve created a new sensor as below, in case anyone who reads this later wants a concrete example. If I don’t get errors for a week or so I’ll call it fixed.

Now to try to delete the old entities from HA… it usually doesn’t seem to want to let them go.

      - name: Forecast Minimum
        unique_id: temperature_forecast_min2
        state: "{{ states('sensor.openweathermap_forecast_temperature_low') | float(0) }}"
        unit_of_measurement: "°C"
2 Likes

It will let them go if you remove the template definitions from your YAML.

I tried that but they seemed to stick around. Eventually I removed them from .storage/core.entity_registry which seemed to worked.

1 Like

So helpful! Thank you very much for sharing. :+1: