Average/Formatting: YAML problem

Hello, I like to display solar power via Awtrix. The raw data should be processed so that it is meaningful and not too long:

Average of the last 10 min.
Formatting: below 9000 in W, above in kW, rounded to whole numbers

As this is too much for me, I had ChatGPT write the template. Looks good, but doesn’t work. Output is code-lines instead of a value.

Where is the problem? Thanks for some help…

sensor:
  - platform: statistics
    name: "Durchschnitt DC Gesamtleistung (10 Minuten)"
    unique_id: "average_dc_power_10min"
    entity_id: sensor.sh20t_a2442602734_total_dc_power
    state_characteristic: mean
    max_age:
      minutes: 10

  - platform: template
    sensors:
      formatted_average_dc_power_10min:
        friendly_name: "Durchschnittliche DC-Leistung (10 Minuten)"
        unique_id: "formatted_average_dc_power_10min"
        value_template: >
          {% set value = states('sensor.average_dc_power_10min') | float(0) %}
          {% if value < 9000 %}
            {{ value | round }}
          {% else %}
            {{ (value / 1000) | round }}
          {% endif %}
        unit_of_measurement: >
          {% set value = states('sensor.average_dc_power_10min') | float(0) %}
          {% if value < 9000 %}
            W
          {% else %}
            kW
          {% endif %}

You can’t do this.

The unit of measurement does not accept templates. String only.

https://www.home-assistant.io/integrations/template/#unit_of_measurement

There’s likely errors in your log about this.

Thanks, removed that part and that error is gone. However, value of “formatted_average_dc_power_10min” remains always at zero, while “sensor.sh20t_a2442602734_total_dc_power” is around 400.

Is it normal that “average_dc_power_10min” does not show up in the entities list?

400/1000 | round = 0.

If you don’t want the value to be rounded, remove | round, or add a number of digits you want it to round to.

That wasn’t it, as the value is >9000, so no /1000 division takes place. I replaced the “sensor.average_dc_power_10min” by the raw "sensor.sh20t… " and it works. So seems that the second part cannot use the averaged value of the first part.