Code syntax

Can someone explain to me if there are differences between the two codes below and which ones?

template:
  - sensor:
      - name: "Generata Totale"
        state: "{{ states('sensor.zcs_hyd_totale_energia_generata') | float(0) }}"
        state_class: total_increasing
        device_class: energy
        unit_of_measurement: "kWh"
        unique_id: generata_totale
        icon: mdi:solar
template:
  - sensor:
      - name: "Generata Totale"
        state: >
          {% set energy = states('sensor.zcs_hyd_totale_energia_generata') | float(0) %}
          {{ energy | round(2) }}     
        state_class: total_increasing
        device_class: energy
        unit_of_measurement: "kWh"
        unique_id: generata_totale
        icon: mdi:solar

I think they are the same except the second one rounds.

2 Likes

OK thank you. But what does round mean? I’m newbie and I still have to learn the basics.

It means limiting to a number of decimal places.

Like the difference between 0.333333333 and 0.33

1 Like

So if I write round(2) I limit to two decimal places, round(3) to three and so on.
Sorry if I take advantage, can you also explain the meaning of float()?

Take a look at the template documentation:

https://jinja.palletsprojects.com/en/latest/templates/#list-of-builtin-filters

These are all filters you can use in Jinja (name of the template language of HA). If you need further or deeper knowledge, refer to the Python documentation as well.

1 Like

I’m curious to know why you added the round filter to the template if you don’t know what it does.

For future reference, you can test your templates in the Template Editor (Developer Tools > Template). It’s a good way to easily experiment and see the result of a template.

I encourage you to copy-paste the following into the Template Editor and observe the results.

{{ states('sensor.zcs_hyd_totale_energia_generata') | float(0) }}
{{ states('sensor.zcs_hyd_totale_energia_generata') | float(0) | round(2) }}

Home Assistant’s templates use the Jinja2 templating language. Many of its features are documented here: Templating. For example, here’s the description of the round filter.

Simply because I copied it. Obviously, being a newbie. But you have given me excellent advice and I thank you.
Ah, I forgot, the two codes above give the same result and I don’t understand why.