Basic templating: Calculating percentages

Hello,

Been doing some templating in configuration.yaml for my Toyota integration, but faced some basic calculation block in defining new sensors. Been looking for the guides but still I cannot figure out what goes wrong, will be a small thing for sure, but I cannot figure it out.

I have the following sensor defined in configuration.yaml and it works great. It defines what percentage I have been driving electric in a week.

      #Toyota EV percentage
      toyota_ev_percentage_week:
        value_template: "{{ states.sensor.xpt_410_current_week_statistics.attributes.EV_distance_percentage }}"
        unit_of_measurement: '%'
        friendly_name: Corolla EV percentage - Week

I would like to use that electric distance percentage to calculate how much did I drive by using fuel. Tried the most obvious calculation by substracting the EV-distance from 100%:

      #Toyota fuel percentage
      toyota_fuel_percentage_week:
        value_template: "{{ 100 | float - states('sensor.xpt_410_current_week_statistics.attributes.EV_distance_percentage') | float }}"
        unit_of_measurement: '%'
        friendly_name: Corolla fuel percentage - Week

But the value of this fuel percentage sensor is 100.0%, so basically my calculation is not working. I have been trying different formats using parentheses etc. but the sensor value still stays 100.0%.

Any clear advice for the noob what I am missing here? :smiley:

That’s an incorrect usage of the states() function.

If you want to use the value of an entity’s attribute, use the state_attr() function.

        value_template: "{{ 100 - state_attr('sensor.xpt_410_current_week_statistics', 'EV_distance_percentage') | float(0) }}"

For more information refer to: Templating - States

Hey, this works! Have to check a bit more detailed the manuals :slight_smile: thanks alot!

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions. For more information, refer to guideline 21 in the FAQ.

1 Like