Value Template, unexpected result on rounding

Hi all,

after spending an hour yesterday trying to understand the root cause for an unexpected result in a value template rounding I figured to bring it up here in the hope someone is able to help.

I have data coming into HA via MQTT. The JSON in question looks like that:

    "DataRecord": [
      {
        "_id": "0",
        "Function": "Instantaneous value",
        "StorageNumber": "0",
        "Tariff": "1",
        "Device": "0",
        "Unit": "Energy (10 Wh)",
        "Value": "1444785",
        "Timestamp": "2021-11-04T07:08:20Z"
      }

I’m using the following mqtt sensor definition in HA:

  - platform: mqtt
    name: "Waermepumpe test kWh"
    state_topic: "mbusmeters/11011192434C1802"
    unit_of_measurement: "kWh"
    value_template: >-
      {%- for rec in value_json.MBusData.DataRecord %}
      {%- if ( 
              ( rec.Function == "Instantaneous value" )
         and  ( rec.StorageNumber == "0" )
         and  ( "Wh" in rec.Unit )
            ) -%}
      {{ rec.Value | float(0) / 1000 | round(2) }}
      {%- endif %}
      {%- endfor %}

What I’m expecting from the input number β€œ1444785” is the output β€œ1444.785” and trying it out in the template editor gives exactly that result.
The sensor value though ends up with β€œ1444.7850.0” and I can’t get my head around on why and where the 0.0 is getting added to the end. I tried multiple different versions of the sensor defintion, bracketing parts of the formula without luck - it always leads to the same result.

Leaving away the round btw gives me β€œ1444785” as expected.

Wild guess:
You have a second record validated by the β€œIf” whose result is β€œ0.0” (the 1444.785 part doesn’t make sense unless you have a typo or a β€œ/1000” somewhere)

1 Like

You were right: It matched a second record given there are ones for different tariffs.
The fix was simple (add the Tariff as a condition) and in case someone uses a similar meter:

    value_template: >-
      {%- for rec in value_json.MBusData.DataRecord %}
      {%- if ( 
              ( rec.Function == "Instantaneous value" )
         and  ( rec.StorageNumber == "0" )
         and  ( rec.Tariff == "1" )
         and  ( "Wh" in rec.Unit )
            ) -%}
      {{ rec.Value | float(0) / 100 | round(2) }}
      {%- endif %}
      {%- endfor %}

Thx koying!