We are using one code analyzer which has a rule like this "Do Not Check Floating Point Equality/Inequality".Below is the example given.
float f = 0.100000001f; // 0.1 double d = 0.10000000000000001; // 0.1 float myNumber = 3.146f; if ( myNumber == 3.146f ) //Noncompliant. Because of floating point imprecision, this will be false { //// } else { //// } if (myNumber <= 3.146f && mNumber >= 3.146f) // Noncompliant indirect equality test { // ... } if (myNumber < 4 || myNumber > 4) // Noncompliant indirect inequality test { // ... } when I tested this code if ( myNumber == 3.146f ) is true so I am not able to understand what this rule is trying to say.
What is solution or code change required for this rule?
Is this rule applicable for C#? When I googled I see more examples of C/C++ for this rule
if (Math.Abs(x - 3.1416f) < 0.0001)to prevent bugs caused by rounding errors.