C#의 Double.IsNaN() 메서드는 지정된 값이 숫자가 아닌 값(NaN, Not-a-Number)인지 여부를 나타내는 불리언 값을 반환합니다.
NaN은 일반적으로 0.0 / 0.0처럼 수학적으로 정의되지 않은 연산의 결과로 발생합니다. 이 메서드를 사용하면 해당 값이 유효한 숫자인지 손쉽게 검사할 수 있습니다.
구문
메서드의 기본 구문은 다음과 같습니다.
public static bool IsNaN (double val);
매개변수 val은 검사 대상이 되는 배정밀도(double) 부동 소수점 숫자입니다. 값이 NaN이면 true, 그렇지 않으면 false를 반환합니다.
예제 1 – 무한대 값 검사
먼저 무한대로 평가되는 값을 IsNaN()으로 검사해 보겠습니다.
using System;
public class Demo {
public static void Main(){
double d = 1.0/0.0;
Console.WriteLine("Double Value = "+d);
Console.WriteLine("HashCode of Double Value = "+d.GetHashCode());
TypeCode type = d.GetTypeCode();
Console.WriteLine("TypeCode of Double Value = "+type);
Console.WriteLine("Positive Infinity? = "+Double.IsInfinity(d));
Console.WriteLine("Check whether the specified value is NaN? = "+Double.IsNaN(d));
}
}실행 결과
Double Value = ∞ HashCode of Double Value = 2146435072 TypeCode of Double Value = Double Positive Infinity? = True Check whether the specified value is NaN? = False
1.0 / 0.0의 결과는 양의 무한대(∞)이므로, Double.IsInfinity()는 True를 반환하고 Double.IsNaN()은 False를 반환합니다. 즉, 무한대는 NaN이 아니라는 것을 알 수 있습니다.
예제 2 – NaN 값 검사
이번에는 정의되지 않은 연산의 결과인 NaN을 IsNaN()으로 검사해 보겠습니다.
using System;
public class Demo {
public static void Main(){
double d = 0.0/0;
Console.WriteLine("Double Value = "+d);
Console.WriteLine("HashCode of Double Value = "+d.GetHashCode());
TypeCode type = d.GetTypeCode();
Console.WriteLine("TypeCode of Double Value = "+type);
Console.WriteLine("Positive Infinity? = "+Double.IsInfinity(d));
Console.WriteLine("Check whether the specified value is NaN? = "+Double.IsNaN(d));
}
}실행 결과
Double Value = NaN HashCode of Double Value = -524288 TypeCode of Double Value = Double Positive Infinity? = False Check whether the specified value is NaN? = True
0.0 / 0의 결과는 NaN이므로, Double.IsNaN()이 True를 반환하는 것을 확인할 수 있습니다.
참고 사항
NaN 값은 자기 자신과도 같다고 판단되지 않기 때문에, d == Double.NaN과 같은 비교 연산자(==)로는 NaN 여부를 확인할 수 없습니다. 따라서 NaN을 검사할 때는 반드시 Double.IsNaN() 메서드를 사용하는 것이 올바른 방법입니다.