Template question, test if value is numeric

Im scraping the webserver of a solar inverter. When it produces energy, I get a number, when it doesnt produce energy, there is a string (something like ’ + + + ’ and some weird characters. Im trying to get a template working to return zero is the value is not numeric. I tried this:

    - platform: scrape
      resource: http://pvserver:[email protected]
      select: 'td'    
      index: 14
      name: "Kostal 1 Vermogen" 
      unit_of_measurement: W
      device_class: energy
      state_class: measurement
      unique_id: Kostal1_vermogen
      scan_interval: 60
      value_template: >
          {% if value is number %}
                {{value}}
          {% else %} 
                0
          {% endif %} 

But it always returns 0. When I just use {{value}}, I do get the correct number during production, but the string otherwise. help?

      value_template: "{{ value | float(0) }}"
1 Like

thanks, Ill give that a shot, but I still want to know how I can test for a numeric value, as I may need it elsewhere

What @123 means is that bu putting | float(0) it will make any string ‘0’, so you can check on > 0

it will make any string ‘0’, so you can check on > 0

Yeah but I cant distinguish between actual 0 and strings or error messages in other fields.

The following will test if the value’s type is a numeric value (integer or float). If the value is a numeric string like '25' then that’s not integer or float but a string and will fail the test (and your template will report 0).

          {% if value is number %}

The following test is a bit more inclusive because it will accept a numeric string as being a number.

          {% if value | is_number %}
2 Likes

Ah, awesome, thanks. Yes, I assume it always is a string, even if a string that represents a number, so thats why my test failed. Ill try the second approach. Can you explain why piping it to is_number behaves differently?

Reference: Templating - Numeric Functions and Filters