Helper: Subtract/Add/divide/multiply two sensor values

Until a ‘Subtract Two Sensors’ Helper is implemented (if ever) here’s how to do it with a simple Template Sensor.

In the following example, the goal is to subtract the value of sensor.subtrahend from the value of sensor.minuend and report the result in sensor.difference.

template:
  - sensor:
      - name: Difference
        state: "{{ states('sensor.minuend') | float(0) - states('sensor.subtrahend') | float(0) }}"

How the template works:

  • states('sensor.minuend') gets the state value of sensor.minuend.
  • State values are always strings (text) even when they appear to be numeric. We convert the string value to a floating point number (a number with decimal places as opposed to integer) using float(0).
  • The 0 in float(0) is a chosen default value. If float is unable to convert the sensor’s state value it will report 0 (the default value). You can set the default value to whatever is best for your application. For example, if the sensor’s value is unavailable then float will report 0.
  • The second half of the template simply performs the same procedure for sensor.subtrahend and then subtracts the resulting value from the value of sensor.minuend.