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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: