Simple template question - basic maths incorrect?

Hi all. I’m using a template in HA to make decisions about cooling based on temperatures. I noticed that things weren’t happening exactly when I expected. I ended putting the template into the template editor then substituting the actual sensor values for the expression and finding something unexpected.

The template below is asking “Is 21 minus 20.7 greater than 0.3”. According to the math I learned at school many years ago the answer should be false, because 21 - 20.7 = 0.3, and 0.3 > 0.3 should evaluate to false.

Have I missed something? Am I having a stupid day, or have I written this incorrectly?

I’m on HA 2024.12.5 - I’m moving away from a custom component that is with HA 2025 so I can’t update right now.

It’s a floating point error:

You can use round() to round to your desired digit.

1 Like

Try:

{{ (21.0 - 20.7) | round(1) > 0.3 }}

But yes - floating point math appears to be difficult for jinja. :smiley:

1 Like

Ah, well spotted. I might have checked for that with multiplication or something, but not for subtraction!

Good solution, thanks :slight_smile:

For programming languages in general. Google “floating point rounding errors”.

If you want to avoid floating point calculations at all the just multiply your numbers by 10 first in this case

1 Like

I would round to a higher number of digits, otherwise this will also return false

{{ (21 - 20.74) | round(1) > 0.3  }}

So maybe use 5 digits precision, even 10 would still work in this case.

1 Like