Hi,
I am trying to subtract two sensor values but the result I a getting is 0W
Can someone please point out what I am doing wrong?
# Calculate Remaining Power
- platform: template
sensors:
remainingpower:
value_template: "{{ ( ('sensor.energy_meter_mains_power') | float) - ( ('sensor.energy_meter_kitchen_power') | float) }}"
unit_of_measurement: 'W'
friendly_name: Remaining Power
1 Like
You’re converting two strings to floats, which since they can’t be interpreted as floats, the float filter is returning zero for each. Zero minus zero is zero.
See:
thanks Phil,
but I think the values I am useing are floats … am I interpreting the calues correctly?
First, all states are strings, even if they look like something else. Second, you’re not using the state of the entity in your template. You’re using a string: ('sensor.energy_meter_mains_power') | float
You’re trying to convert the string 'sensor.energy_meter_mains_power'
to a float, not the state of the sensor.energy_meter_mains_power
entity. See the doc page I pointed you to to see how to get the state of an entity using its entity_id.
thanks Phil, I was not aware that values are always stings.
The below is working, but I am getting several decimal places like the below. The round(1) commands are not enough?
# Calculate Remaining Power
- platform: template
sensors:
remaining_power:
value_template: "{{ ( states('sensor.energy_meter_mains_power') | float | round(1)) -
( states('sensor.energy_meter_kitchen_power') | float | round(1)) -
( states('sensor.water_heater_watts') | float | round(1))}}"
unit_of_measurement: 'W'
friendly_name: Remaining Power
2 Likes
You’ve been bit by the “floats don’t have infinite precision” fact. First, you don’t need to round each term of the equation, you can round the sum, which is probably better anyway. But, still, this can happen. What you really need to do is not round, but specify an output format. E.g.:
# Calculate Remaining Power
- platform: template
sensors:
remaining_power:
value_template: >
{{ '%0.1f' | format(states('sensor.energy_meter_mains_power') | float -
states('sensor.energy_meter_kitchen_power') | float -
states('sensor.water_heater_watts') | float) }}
unit_of_measurement: 'W'
friendly_name: Remaining Power
9 Likes
worked perfectly … thanks for taking the time to explain!
1 Like