Struggling with a template sensor for cost of energy

I have an energy sensor to track my EV charging and want to create a template sensor that multiplies the kwh value of the sensor by the price-per-kwh value of an energy tarriff sensor. The resulting sensor is giving a value of ‘Unavailable’. I’m not a pro at this. Can anyone spot my error in the below yaml?

i3_120_charging_energy_weekly_cost:
        value_template: "{{ (states.sensor.electric_tariff_rate.state * states.sensor.i3_120_charging_status_energy_weekly.state | float) | round(2) }}"
        unit_of_measurement: 'GBP'
        unique_id: 44c6e9a9aa4df7378598dab2c3fbf402

Hi !

Try :

i3_120_charging_energy_weekly_cost:
        value_template: "{{ (float(states('sensor.electric_tariff_rate.state'), 0) * float(states('sensor.i3_120_charging_status_energy_weekly'), 0)) | round(2) }}"
        unit_of_measurement: 'GBP'
        unique_id: 44c6e9a9aa4df7378598dab2c3fbf402

Adding some context sorry :
In docs it’s stated :

Avoid using states.sensor.temperature.state , instead use states('sensor.temperature') . It is strongly advised to use the states() , is_state() , state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).

And, before doing maths on sensors states, get them to float, you will do maths between floats and you will get floats at the end.
And don’t forget the default value for float filter => float(value, default)

Thanks so much for the detailed reply. Your changes seem to have fixed the ‘Unavailable’ problem. I’m now seeing a 0.0 GBP value but given that the energy sensor state is 53 (referring to kwh this week) it should have a value now. If relevant the dev console calls the value “state_class: total_increasing” - does that change the way I need to work with it?

(float(states('sensor.electric_tariff_rate.state')

Should be

(float(states('sensor.electric_tariff_rate')
1 Like

@Holdestmade is right ! Copy paste gone wrong…

That was it guys, man I love this community! Thanks @SNoof85 & @Holdestmade :slight_smile:

1 Like

The solution was spread across two helpful replies so I’m pasting the final yaml in this reply so I can mark the solution in one place

i3_120_charging_energy_weekly_cost:
        value_template: "{{ (float(states('sensor.electric_tariff_rate'), 0) * float(states('sensor.i3_120_charging_status_energy_weekly'), 0)) | round(2) }}"
        unit_of_measurement: 'GBP'
        unique_id: 44c6e9a9aa4df7378598dab2c3fbf402
1 Like

And if anyone is interested I used the excellent ‘powercalc’ integration (in HACS) to create the energy sensor entity used in this cost sensor since my EV charger has no HA integration.