Pipe float give weird result

Hello,

Yesterday I had a weird result in an automation and I saw that the | float was causing it.

Example:

{{ 24.1 | float - 24.2 | float }}

returns “-0.09999999999999787”

I searched a bit on google and on this forum and I found some posts mentionning that it could come from the “Machine epsilon”. All the posts were related to the “round” function that is causing that. But here I don’t use the round function and the result is not what I expected.

I’m not saying that it is not normal, I just would like to understand.
Is it a best practice to always add | round(X) after a | float to get the expected result ? And is it safe ?
Also I don’t understand why everybody mention the issue from the round function. In my case, the round seems to be more a solution that a problem. Did I miss something ?

That is exactly what it is.

Short answer, floats are not accurate.
Long answer:
Why Floating-Point numbers are inaccurate or have error. | Level Up Coding (gitconnected.com)

You can compare it with the problem we have at writing down the result of 1 divided by 3. We just can’t accurately do it. A computer has the same issues with floats, but for different numbers.

Ok Now I understand why it happens but I still don’t know how to solve it.

Is it a best practice to always add | round(X) after a | float to get the expected result ? And is it safe ?

It’s not caused by the float filter. It’s the calculation itself.