Code help please

{% set over_forecasts = states('input_number.over_forecasts') | float  %}  
   {% set under_forecasts = states('input_number.under_forecasts') | float %}
    {% set num_days = (states('input_number.over_forecasts') + states('input_number.under_forecasts')) | round(0) %} 
    {% if num_days > 0 %}
      {{ ((over_forecasts / num_days) * 100) | round(2) }}
    {% else %}
      0
    {% endif %}

In the above code, input_number.over_forecasts = 5 and input_number.under_forecasts = 1

When I run the code, I get the error below:

Error rendering data template: ValueError: Template error: round got invalid input ‘5.01.0’ when rendering template ‘{% set over_forecasts = states(‘input_number.over_forecasts’) | float %} {% set under_forecasts = states(‘input_number.under_forecasts’) | float %} {% set num_days = (states(‘input_number.over_forecasts’) + states(‘input_number.under_forecasts’)) | round(0) %} {% if num_days > 0 %} {{ ((over_forecasts / num_days) * 100) | round(2) }} {% else %} 0 {% endif %}’ but no default was specified

So it seems like, instead of getting 5+1 = 6, the automation is getting 5 + 1 = 5.01.0. Both of the entities I’m using are integers rather than strings, so I can’t understand why this is happening?

It looks to me that this is the problem, you aren’t converting your values to floats when you do the addition like you do on the first statement. You could also convert them to int if you don’t need the float.

{% set num_days = ( int(states('input_number.over_forecasts'), 0) + int(states('input_number.under_forecasts'), 0))  %}

@CO_4X4 Thanks so much for this. I was tearing my hair out trying to work this one out!

1 Like