Helper for power calculation not negative value

Hi,

I want to create one entity to display my power consumption or production. I have made one helper with the template sensor with state value: {{ states('sensor.dsmr_reading_electricity_currently_delivered')|float(0) - states('sensor.dsmr_reading_electricity_currently_returned')|float(0) }}
this works fine except, if my production is greater then my consumption it shows a zero instead of a negative value. How/where do I set negative numbers are allowed in the helper?

Would this work?

{%set d = states('sensor.dsmr_reading_electricity_currently_delivered')|float(0)%}
{%set r = states('sensor.dsmr_reading_electricity_currently_returned')|float(0)%}
{{d-r}}

@worldvirus’s version is functionally identical to yours, @locutusweb.

I cannot see any reason why your helper should not produce negative values. When you next have a situation where your production is greater than your consumption, please post a screenshot of the Developer Tools / States page for those two sensors. Looks like this:

Is your return sensor negative or positive when you return? If it is negative, you might be counting it as use by subtracting instead of adding. Look at the invidual values when the outcome is off.

1 Like

Thanks to you all! Great community at HA!

I am not at home ATM, so I can’t check the developer tools. I do that tonight.

Meanwhile I am learning at the go. I was assuming the float | 0 meant no decimals, but it returns a zero when there is no numeric value. With sensor.dsmr_reading_electricity_currently_delivered I can do calculations, but with sensor.dsmr_reading_electricity_currently_returned I can’t because it always 0 (zero) even if my dashboard shows a value of 3.100 Watts for sensor.dsmr_reading_electricity_currently_returned right now. If this is a string, than the float option should convert it to numeric, right?

All sensor states are strings, and |float(0) will attempt to convert to a number falling back on 0 if it fails.

We’d need to see the actual state of the “currently returned” sensor to be able to diagnose further, but the problem is not in your template. A screenshot from your phone would do:

Thanks for helping me out.

I have made some screenshots to show this sensor.dsmr_reading_electricity_currently_returned sensor report data and also a screenshot from developer tools.

The actual production:

(I can only attach one image at a time)

SOLVED! It’s hard to see, but there was a space between the device name and the last '. Removing the space made the helper work. Thanks to all.

1 Like