Setting a float value isn't working

Hello,

I have the below code:

if (x == -0.01) x = 0;
Serial.println(x);

x is a float. For some reason, despite setting x to 0, it still prints -0.01 when x = -0.01 and I'm not sure as to why that is.

Any help would be greatly appreciated. Thank you.

You should never attempt to test for equality with the 'float' datatype as they are only approximations. Instead, test if your value lies within some small range centered on the target. In your case the range might be between -0.011 and =0.009.

Thank you for your response. Below is a solution:

if (xAvg > -0.02 && xAvg < 0) xAvg = 0.0;

It turns out that trying to write 1/100 in binary is like trying to write 1/3 in decimal.

Indeed!

https://www.h-schmidt.net/FloatConverter/IEEE754.html

I don't remember the details, but I think I heard it from the dozenal math people about some big accident that NASA had because they forgot this when they were letting the computer convert metric units. Their point being, I think, that unit conversion among imperial units, which has the same mathematical advantages in a dozenal system that metric units have in the decimal system, is exact in binary thus somehow implying that we should all count by 12s.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.