Prevents using `==` and `!=` operators on floats and doubles

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: csharp-best-practices/float-equality

Language: C#

Severity: Error

Category: Best Practices

Description

Floating point math is inherently imprecise, so checking strict equality to a float or double will very likely lead to unexpected bugs.

For example: Input

var a = 0.1f;
var b = 0.2f;
var c = 0.3f;
Console.WriteLine($"{a + b == c}");

Output

False

(Note: exact results can vary depending on the compiler used)

Non-Compliant Code Examples

class NonCompliant
{
    public static void Main()
    {
        float foo = 1.2345f;

        if (foo == 1.2345f) { /* ... */ }

        if (4.567d == 4.567d) { /* ... */ }
        if (4.567f != 4.567f) { /* ... */ }

        bool isEqual = foo == 1.2345f;
    }
}

Compliant Code Examples

class Compliant
{
    public static void Main()
    {
        float foo = 1.2345f;
        var tolerance = 0.000000001f;
        if (Math.Abs(foo - 1.2345f) < tolerance) { /* ... */ }
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis