Convert to abs in template sensor

I am trying to create template sensor that shows power exported to grid in positive values. In case, there’s no export to grid, it should show 0.

I came up with this but it shows N/A when saved.

{% if state(sensor.active_power) < 0 %}
  {{ state(sensor.active_power)|abs }}
{% else %}
 {{ '0' }}
{% endif %}

States are strings. You need to convert the state to a number first, before doing any mathematical operations or comparisons.

{% if state(sensor.active_power)|float(0) < 0 %}
  {{ state(sensor.active_power)|float(0)|abs }}
{% else %}
  {{ 0 }}
{% endif %}

It still shows N/A:

despite active_power is now -157W

Quotes and states() with an s:

{% if states('sensor.active_power')|float(0) < 0 %}
  {{ states('sensor.active_power')|float(0)|abs }}
{% else %}
  0
{% endif %}

Alternatively:

{{ min(0, states('sensor.active_power')|float(0)) * -1 }}
1 Like