Template math does not work

Hello,

i have the following template, wich is not work. But, i dont know why. Can anyone explain me what i doing wrong?

strom_momentan is working
strom_momentan_temp is working
strom_seit_meldung issnt working

if i set “strom_seit_meldung” to only states(‘sensor.strom_gesamt’) i become the entry from “strom_gesamt”.

sensor:
  - platform: mqtt
    name: "strom_momentan"
    state_topic: "strom/stromzaehler/strom"
    unit_of_measurement: 'W'
    qos: 1
#    value_template: "{{(value|round(2))}}"
  - platform: mqtt
    name: "strom_gesamt"
    state_topic: "test/stromzaehler/kwh"
    unit_of_measurement: 'kWh'
    qos: 1
    value_template: "{{(value|round(0))}}"

  - platform: template
    sensors:
     strom_momentan_temp:
      friendly_name: "Stromverbrauch Momentan"
      unique_id: strom_momentan_id
      unit_of_measurement: 'W'
      value_template: >-
           {{ (3600000/(120*(states.sensor.strom_momentan.state)|round(2)))|round(2) }}
           
     strom_seit_meldung:
      friendly_name: "Stromverbrauch seit letzter Meldung"
      unique_id: strom_gesamt_id
      unit_of_measurement: 'kWh'
      value_template: >-
        {% set strom_json = {
        "letzteMeldung": 175570,
        "preiskwh": 0.293
        } %}
        {{ ((states('sensor.strom_gesamt') - strom_json.letzteMeldung) * strom_json.preiskwh) | round(2) }}

if i try this, the template “strom_seit_meldung” is unavaible in the dashboard sensor card.

Thank You very much. I try this the last hours…

schmucke

An entity’s state value is always a string. That means this:

states('sensor.strom_gesamt')

will return a string value. If you want to do math with it you must convert it to either an integer, using the int filter, or a floating-point number using the float filter.

{{ ((states('sensor.strom_gesamt') | float - strom_json.letzteMeldung) * strom_json.preiskwh) | round(2) }}
1 Like

It is so easy if i know what to do. Thank you very much for the hint, that a state is always a string. its so logical… :man_facepalming:

1 Like