How to use arithmetic to do subtraction and addition in the home assistant template,

how to use arithmetic to do subtraction and addition in the home assistant template, for example I have a case, the water dispenser has a capacity of 19 liters of water, and I have a sensor to detect water needs every day. I want to know the difference in the amount of water available, by subtracting the tank capacity from the daily water requirements, the value of which can be displayed on the dashboard. i try with this code:

sensor:
  - platform: template
    sensors:
      water_left:
        friendly_name: "water_left"'
        unit_of_measurement: "liter"
        value_template: "{{ state_attr('sensor.capasity', 'value') | int - state_attr('sensor.daily.water', 'value') | int }}"   '

but result is unavalable.please help

https://community.home-assistant.io/t/how-to-help-us-help-you-or-how-to-ask-a-good-question/114371#oneone-format-it-properly-16

You need ``` , not ‘’’

First delete the last character in the friendly_name line.

Secondly I have several times found the Jinja interpreter to read the last | int as a conversion of the subtraction result and not of the last value in the subtraction formula, so I always use parentheses now.

value_template: "{{ (state_attr('sensor.capasity', 'value') | int) - (state_attr('sensor.daily.water', 'value') | int) }}"

And lastly there is also a last character in the end of the value_template line that needs to be deleted.

Multiple issues here, some of which have been pointed out:

  • this is a legacy format template sensor, would recommend using modern configuration (docs)
  • extra ' at the end of the friendly_name line
  • are you certain about sensor.capasity rather than “capacity” spelling?
  • I don’t believe you can have sensor.daily.water — should it be sensor.daily_water?
  • are the values really stored in value attributes of each sensor, or are they in the state? If they really are in attributes, you may not need the |int as attributes can be real numbers whereas states are always strings.
  • extra ' at the end of the value_template line

You can create template sensors like this via the UI:

  • no YAML formatting difficulties
  • sensor name autocorrect
  • preview value visibility

Go to Helpers, and create a Template Sensor like this (where I’ve guessed your actual entity IDs and used |float(0) to allow for non-integer values and a default of 0 if the sensor isn’t available):

State template in that screenshot is:

{{ states('sensor.capacity')|float(0) - states('sensor.daily_water')|float(0) }}

You can also try out your templates under Developer Tools / Template before using them in a sensor:

thank you very much,problem solved. you make myday :pray: :pray: :pray:

1 Like