[Solved] How do I test whether a string can be converted to a floating point number?

I found out by experiment that the float filter in jinja treats a non-existent or non-numeric input as a fatal error – i.e. it stops the automation dead. I therefore need a way of testing whether it is going to work before calling it.

The code in question is:

variables:
  local_event_description: !input event_description
  local_zone_calendar: !input zone_calendar

[…]

      - service: input_text.set_value
        data:
          value: "{{ state_attr(local_zone_calendar, 'description' ) }}"
        target:
          entity_id: !input event_description

[…]

      - service: input_number.set_value
        data:
          value: >-
            {% set temperature_text = states(local_event_description).split('#')[1] %}
            {{ '%0.1f' | format(float(temperature_text)) }}
        target:
          entity_id: !input event_temperature

… where

  • zone_calendar is a local calendar with a description field that contains a temperature between hashes (and that works fine)
  • event_description is an input_text helper and
  • event_temperature is an input_number helper

The code takes the text of the description in a local calendar event and extracts a temperature specified as a floating point number to one decimal place between two hashes.

For the full code see AndySymons/heating_x.yaml

I could easily test for temperature_text being longer than 0 but how do I test whether it is a valid input to float?

I usually use the float filter which provides a default if it can’t be converted.

 {% set temperature = (states(local_event_description).split('#')[1])|float(-999) %}

So if temperature is -999 then you know it can’t be converted.

1 Like

Use this test, |is_number e,g, {% if temperature_text|is_number %}

Only if you fail to supply the float filter with a default value.

And that error will tell you all of that in the log.

OP, what did your log say?

I tried that but the test is always false (as has been noted on other forums)

How do I combine that with formatting to one decimal place?

The only time that test returns false is when the string can not be converted to a number.

{{ '%0.1f' | format(temperature_text | float(0)) }}

Example

Thanks. Sorted :slightly_smiling_face:

Thanks. I will do some more tests on that but I know I am not the only one to have had problems with is_number, and the default value for float has fixed my immediate issue.

I’ve been using it extensively since it was introduced and there has never been an issue with it. Can you find these ‘problem’ posts?

Sorry, I failed to keep notes and cannot find them now with Google, so I will have to withdraw my comment. I am travelling for the next couple of months but will do some more tests using is_number when I get home.