#78 – Checking for Special Floating Point Values

You can check a float or double in C# to see if it has one of the following special values: Infinity, Negative Infinity, or Not-a-Number (NaN).

 float f1 = 0.0f / 0.0f;        // NaN
 float f2 = 1.0f / 0.0f;        // Infinity
 float f3 = -1.0f / 0.0f;       // -Infinity

 Console.WriteLine(float.IsNaN(f1));     // True
 Console.WriteLine(float.IsInfinity(f2));  // True
 Console.WriteLine(float.IsPositiveInfinity(f2));    // True
 Console.WriteLine(float.IsNegativeInfinity(f3));    // True

The float and double classes also have static fields that let you set special values directly.

 // Setting special values
 float f1 = float.NaN;
 float f2 = float.PositiveInfinity;
 float f3 = float.NegativeInfinity;