Rounding temperature values

Hello

I want to round various temperature values to half a degree .
Example:
23.3 to 23.5
4.69 to 5.0
12.2 to 12.0

This is my YAML Code
  - platform: template
    sensors:

      temperature_indoor_roundet:
        friendly_name: "Temparatur Indoor"
        unit_of_measurement: "°C"
        value_template: "{{ states('sensor.indoor_temperature') | float+ 0.5 | round(1) }}"

How do I do this right?

You could try something like this in kdeveloper tools > templates…then replace the figure (1.3) by your sensor

{{ (1.3 * 2) | round(0) /2 }}
2 Likes
{{ (states.sensor.indoor_temperature.state | float * 2) | round(0) /2 }}
1 Like

thank you so much!
But I have no idea how this works.

The math or the Jinja2?
In Jinja2,

{% is surrounding regular code
{{ is the return of the code
| float will ensure that you convert the state into a float number
| round(0) will remove everything after the decimal point

In HA
states.sensor is all sensors states, then it is yours that we pick.

The math behind is up-to-you but think about it with your exemples and one of mine

23.3 -> 46.6 -> 46 -> 23
4.69 -> 9.38 -> 9 -> 4.5
12.2 -> 24.4 -> 24 -> 12
1.6 -> 3.2 -> 3 -> 1.5

In the last exemple, 1.6 multiplied by 2 will get over 3 that will lead to 1.5 as the final result
On the other hand, 1.4 doesn’t, it will be 2.8 that will later become 2 and then 1. You got the idea, right?

1 Like

Btw, to be sure that you’re not getting a template error, you can add a | default(0)

{{ (states.sensor.indoor_temperature.state | default(0) | float * 2) | round(0) /2 }}

Like so, if your sensor is unknown or undefined, it will be replaced by 0 and the remaining of the computation will succeed, otherwise, multiplying and dividing will fail.

:pray: :+1: