Templating with default values

I have this in one of my templates which gives me division by zero errors in the log:
(pasting it on multiple lines for better reading)

{{ 
'%.2f'%(
    (states('sensor.vehicle_bat_ced') | default(0) | float) * 100 
  / (states('sensor.vehicle_odo') | default(1) | float) 
)| float 
}}

Three things I would like to know:

  • is default(0) a supported function? I can’t find any documentation on it.
  • what will states('sensor.vehicle_odo') return, if this sensor is not available? (After restarting HA, Lovelace shows “entity not available” until the car sends new values to HA)
  • will default(1) work atall? I suspect it, as I have the division by zero in the logs.
1 Like

Go to Developer Tools -> Templates and try out your template there

2 Likes

I tested there.
(states('sensor.vehicle_odo') gives unknown and default(1) does not change the value.
The cast to | float changes the value to 0.0 et voila - division by zero.

For now I solved it with

... / (states('sensor.vehicle_odo') | float + 1

I can live with one off on 15k :slight_smile:

1 Like

| float(1) would do the same

1 Like

To answer my own questions:

  • default(0), still no information on this. Developer Tools > Templates renders 123 for {{ null | default(123) }} so it is a supported filter, but rather useless for my case, as it will not work on unknown which is returned by states() if an entity is not available.
  • Developer Tools → Templates is good for any questions on return values of expressions
  • use cast to float or int, to get a default value on bogus states:
{{  states("notexistant") | default(123) }} > unknown
{{  states("notexistant") | int(2) }} > 2
3 Likes

it’s jinja, it’s covered in the jinja documentation. This language is just used by HA, look there for methods & filters that HA doesn’t cover in the docs.

1 Like

Hi,
I guess this is the explanation for the expected behavior:

  1. While the float and int filters do allow a default fallback value if the conversion is unsuccessful, they do not provide the ability to catch undefined variables.

So, as soon as the the variable is undefined you will get a division by zero.

Take care

 Frank
2 Likes