[solved] Value Template sum with negative values

I’m trying to create a sensor template which is sum up some other sensors.
For debugging purposes I was playing around with the templates section where I can test realtime.

Var 1: {{ states('sensor.PV_Eigenverbrauch_Aktuell') }}
Var 2: {{ states('sensor.PV_Power') }} 
Sum: {{ states('sensor.PV_Eigenverbrauch_Aktuell') + states('sensor.PV_Power') }}

The result looks like:

Var 1: 0
Var 2: -2550
Sum: 0-2550

Does anyone know how I can bring jinja to sum up negative values?

You were concatenating strings with “+”. With the template below you can add integers, you can also use floating point ( | float ).

Sum: {{ states('sensor.PV_Eigenverbrauch_Aktuell') | int + states('sensor.PV_Power') | int }}

Thanks, this worked out.

to me it continued to give a negative value, I solved thanks to a user of the HA group on Discord in this way

value_template: "{{ states('sensor.produzione_istantanea') | int - states('sensor.consumo_istantaneo') | int  if states('sensor.produzione_istantanea') | int - states('sensor.consumo_istantaneo') | int > 0 else 0 }}"

If you use a variable then Home Assistant only needs to perform the subtraction once (not twice):

value_template: >
  {% set diff = states('sensor.produzione_istantanea') | int - states('sensor.consumo_istantaneo') | int %}
  {{ diff if diff > 0 else 0 }}
1 Like