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;

Indeed!

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

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