Template Sensor to calculate cost of energy

For about a year, I have had a template sensor calculating my energy costs with:

sensor:
  hvac_annual_cost:
    unique_id: 3837268e-ccb7-4a0d-84f5-691331725f8e
    friendly_name: "Heating/Cooling Annual Cost"
    value_template: "${{ ((states('sensor.heat_pump_air_handler_yearly_energy') | float * states('input_number.electricity_cost') | float )) | round(2) }}"

I decided to update the format to:

sensor:
  - name: "hvac_annual_cost"
    #device_class: "monetary"
    #unit_of_mearsurement: "USD"
    #state_class: "total"
    unique_id: "3837268e-ccb7-4a0d-84f5-691331725f8e"
    state: "${{ ((states('sensor.heat_pump_air_handler_yearly_energy') | float * states('input_number.electricity_cost') | float )) | round(2) }}"

With the updated sensor setup I get a couple of issues. When I uncomment the unit_of_measure, I get an error in HA Studio Code Server stating “Property unit_of_measurement is not allowed.” Also, if I uncomment device_class and/or state_class, the sensor becomes unavailable.

If I create a template sensor using a Helper, the template sensor works fine.


Any suggestions or help would be appreciated.

Lots of things wrong with that. Not least of which is that you are including the unit in the state. You cant do that if you want it to be treated as a number (monetary class).

template:
  - sensor:
      - name: "HVAC Annual Cost"
        unique_id: 3837268e-ccb7-4a0d-84f5-691331725f8e
        state_class: measurement
        device_class: monetary
        unit_of_mearsurement: USD
        state: "{{ (states('sensor.heat_pump_air_handler_yearly_energy') | float * states('input_number.electricity_cost') | float ) | round(2) }}"
        availability: "{{ states('sensor.heat_pump_air_handler_yearly_energy') | has_value and states('input_number.electricity_cost') | has_value }}"

Also take note of the misspelling

unit_of_mearsurement:
           ^
         remove
1 Like

I appreciate the feedback. I’m not sure I understand your statement “…you are including the unit in the state.” Could you explain this in more detail?

Also, thanks for the “Availability” addition and formatting corrections.

NVMD - I see what your referencing…must have been way too late :slight_smile: Again, thanks for the help.

@mekaneck Geez, I bet I looked at that 100 times, suspecting something silly, and still overlooked the typo! Thanks.