CodeQL documentation

Equality check on floating point values

ID: cs/equality-on-floats
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - reliability
   - correctness
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

Directly comparing two floating point values is dangerous due to the imprecision encountered when storing and performing arithmetic on them.

Recommendation

Floating point numbers should be treated as equal if the difference between their values is within a certain margin of error. The appropriate margin of error depends on the situation in which it is used.

As a cautionary note, floating-point comparison is a non-trivial topic, and our documentation here takes a pragmatic approach rather than trying to do it justice. You are strongly advised to consult the references for further information.

Example

Although you might expect this example to output “True” it actually outputs “False” due to the imprecise way floating point arithmetic is performed.

class EqualityCheckOnFloats
{
    public static void Main(string[] args)
    {
        Console.WriteLine((0.1 + 0.2) == 0.3);
    }
}

The class should be changed to perform a comparison with a tolerance value as in the following example.

class EqualityCheckOnFloatsFix
{
    public static void Main(string[] args)
    {
        const double EPSILON = 0.001;
        Console.WriteLine(Math.Abs((0.1 + 0.2) - 0.3) < EPSILON);
    }
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy