Need help formatting temperature values (rounding and removing decimals)

Hi,

I’m trying to format my temperature values so they look like this:

21.1 = 21 °C
21.4 = 21.5 °C
22.8 = 23 °C

I think you can use if statements to achieve this, but I can’t figure out the syntax to get this to work. I would be grateful for some guidance on this. :slightly_smiling_face:

Not very elegant but, how about this:

{% set my_value = "23.7" %}
{% set rounding = {'0':'', '1':'', '2':'', '3':5, '4':5, '5':5, '6':5, '7':'', '8':'', '9':''} %}
{% set increment = {'0':0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':1, '8':1, '9':1} %}
{{ ((my_value | int) + increment[my_value[-1:]]) ~ '.' ~ rounding[my_value[-1:]]}}

This assumes that you can use templating in the UI card or theough a Template Sensor.

The math part works, but results in a extra dot when rounded to the nearest whole number e.g. 21 °C becomes 21. °C (note the dot right after the number).

Use | round(1, 'half', 0)

The rounding works, but won’t remove the decimal (xx.0) when whole number.

I finally managed to solve this, by using an if statement:

{% set state = states.sensor.lumi_lumi_weather_temperature_2.state %}
{% if state == 'unavailable' %}  # This checks if the device is unreachable e.g. dead battery
  Error!
{% elif state == state|int %} # Some action is taken if state is an integer (whole number) e.g. 21 and 21.0 counts.
  {{ state | round(0) }} °C # Round down or up and remove any decimals.
{% else %} 
  {{ state | round(1, 'half') | replace('.0','') }} °C # Round down or up by half (0.5) and if e.g. '21.0', remove the '.0', so it becomes '21'.
{% endif %}

Shorter version using recommended way to access sensor state:

{{ ((states('sensor.lumi_lumi_weather_temperature_2')|float(0)*2)|int/2)|string|replace('.0','') }}
1 Like

Also you can’t have non-numeric results if you have a unit of measurement (your “Error” option). If this happens your template will fail to load.

Use an availability template.