#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;

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers