- 필수 기능
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- 디지털 경험
- 소프트웨어 제공
- 보안
- 로그 관리
- 관리
- 인프라스트럭처
- ci
- containers
- csm
- ndm
- otel_guides
- overview
- slos
- synthetics
- tests
- 워크플로
ID: csharp-best-practices/float-equality
Language: C#
Severity: Error
Category: Best Practices
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)
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;
}
}
class Compliant
{
public static void Main()
{
float foo = 1.2345f;
var tolerance = 0.000000001f;
if (Math.Abs(foo - 1.2345f) < tolerance) { /* ... */ }
}
}
|
|
For more information, please read the Code Analysis documentation
Identify code vulnerabilities directly in yourVS Code editor
Identify code vulnerabilities directly inJetBrains products