Add default value to json based template sensor

I have the following json template.

# Balcony Door Sensor battery level
  - name: 'Balcony Door Sensor Battery'
    state_topic: 'helium/sensor/rx'
    value_template: "{{ value_json.battery if value_json.battery is defined else states('sensor.balcony_door_sensor_battery') | round(1) }}"
    unit_of_measurement: "%"
    device_class: "battery"

But home assistant complains that sensor.balcony_door_sensor.battery doesnt have a default value, and I’m not quite sure how to add one.

Home Assistant gives:
ValueError: Template error: round got invalid input 'unknown' when rendering template '{{ value_json.battery if value_json.battery is defined else states('sensor.balcony_door_sensor_battery') | round(1) }}' but no default was specified

The problem is that you are trying to round a string.

all states are strings so states('sensor.balcony_door_sensor_battery') becomes a string even if it looks like a number.

you need to add the float() function to convert it to a float value:

value_template: "{{ value_json.battery if value_json.battery is defined else states('sensor.balcony_door_sensor_battery') | float() | round(1) }}"

but that still could give you the same error if the value of sensor.balcony_door_sensor_battery hasn’t been initialized yet.

That wouldn’t be a big deal for me if it only happened at startup when things aren’t fully initialized becasuse once things do get initialized then the template will work normally.

But I know sonme are OCD about errors in the logs so if you want to fix it you will need to figure out what you want as a default in the template:

value_template: "{{ value_json.battery if value_json.battery is defined else states('sensor.balcony_door_sensor_battery') | float(some_default_number_here) | round(1) }}"

Round doesn’t need numbers, it works off strings or numbers.

Round needs a default if it fails to convert a string to a number. Also you can apply the round to the whole if statement.

    value_template: "{{ (value_json.battery if value_json.battery is defined else states('sensor.balcony_door_sensor_battery')) | round(1, default=0) }}"
1 Like

Thanks, that’s a nice solution! Cheers!