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).
1
2
3
4
5
6
7
8
| float f1 = 0.0f / 0.0f; // NaNfloat f2 = 1.0f / 0.0f; // Infinityfloat f3 = -1.0f / 0.0f; // -InfinityConsole.WriteLine(float.IsNaN(f1)); // TrueConsole.WriteLine(float.IsInfinity(f2)); // TrueConsole.WriteLine(float.IsPositiveInfinity(f2)); // TrueConsole.WriteLine(float.IsNegativeInfinity(f3)); // True |
The float and double classes also have static fields that let you set special values directly.
1
2
3
4
| // Setting special valuesfloat f1 = float.NaN;float f2 = float.PositiveInfinity;float f3 = float.NegativeInfinity; |

