Sensor Template not Rounding to n Decimal Places

Hi,

I’ve got an issue where round() not working in my sensor template. Does anyone have any ideas what I might be doing wrong?

Excert from configuration.yaml: -

sensor:
  - platform: template
    sensors:
        energy_cost_total:
            friendly_name: "Total Energy Cost"
            value_template: '£{{ states("sensor.dcc_sourced_smart_electricity_meter_cost_today") | float | round(2) 
			                + states("sensor.dcc_sourced_smart_gas_meter_cost_today")| float | round(2) }}'

What’s displayed sometimes in the dashboard when the sensor is added to a card: -

Total Energy Cost £1.9100000000000001

Hi Mat Hardaker,

Rounding the operands doesn’t help you other than make it less accurate. You need to round the answer. enclose the whole thing it parens and cast it to round, get rid of the ones in the middle.

I think you want to only round once.

'£{{ (states("sensor.dcc_sourced_smart_electricity_meter_cost_today") | float + states("sensor.dcc_sourced_smart_gas_meter_cost_today") | float) | round(2) }}'
1 Like

Thanks I understand what I was doing wrong now. round() still didn’t quite do what I wanted £5.800000000001 was being displayed as £5.8 so I slightly tweaked with format: -

sensor:
  - platform: template
    sensors:
        energy_cost_total:
            friendly_name: "Total Energy Cost"
            value_template: '£{{ '%0.2f'| format(states("sensor.dcc_sourced_smart_electricity_meter_cost_today") | float
                                         + states("sensor.dcc_sourced_smart_gas_meter_cost_today")| float) }}'

Interesting. The above works in Template Editor but when added to configuration.yaml HA can’t parse it: -

Configuration errors
Error loading /config/configuration.yaml: while scanning for the next token
found character ‘%’ that cannot start any token
in “/config/configuration.yaml”, line 18, column 35