Formula error

I just can’t figure out why the statement below keep on made the 1st statement correct while supposing should go to “else” statement

          {% if states('sensor.current_kwh_month') > states('sensor.kwh_tier1') %}
            {{ ( states('sensor.kwh_tier1')|float * states('sensor.kwh_price_tier1')|float ) | round(2) }}
          {% else %}
            {{ ( states('sensor.current_kwh_month')|float * states('sensor.kwh_price_tier1')|float ) | round(2) }}
          {% endif %}

sensor value as below:
sensor.current_kwh_month=60
sensor.kwh_tier1=200
sensor.kwh_price_tier1=0.218

result=43.60(200x0.218) but I expecting the result=13.08(60x0.218)

States are strings. You are comparing strings not numbers. Strings are compared letter by letter left to right so ‘60’ is bigger than ‘200’ just like ‘zen’ is later in the dictionary alphabetical order than ‘triangle’ (even though the latter has more letters). Try this:

{% if states('sensor.current_kwh_month')|float(0) > states('sensor.kwh_tier1')|float(0) %}
1 Like

@tom_l just try it, is working ! Thanks for your advise. I wondering what is the “0” mean which behind the float as some of my statement didn’t put the “0” at the back.

If your sensors return a value that is not able to be converted to a number (e.g. ‘unavailable’) the the default value of ‘0’ is substituted. You should always include a default value to prevent errors or your templates may not load at start up.

1 Like

@tom_l , now I understand. Thanks again.

1 Like