C# Float and Double Special Values
Description
Floating-point types have values that certain operations treat specially. These special values are
- NaN (Not a Number)
- PositiveInfinity
- NegativeInfinity
- -0
The float and double classes have constants for NaN, PositiveInfinity, and NegativeInfinity, as well as other values.
For example:
Console.WriteLine (double.NegativeInfinity); // -Infinity
The constants that represent special values for double and float are as follows:
Double constant | Float constant |
---|---|
double.NaN | float.NaN |
double.PositiveInfinity | float.PositiveInfinity |
double.NegativeInfinity | float.NegativeInfinity |
-0.0 | -0.0f |
Example
Dividing a nonzero number by zero results in an infinite value. For example:
Console.WriteLine ( 1.0 / 0.0); // Infinity
Console.WriteLine (-1.0 / 0.0); // -Infinity
Console.WriteLine ( 1.0 / -0.0); // -Infinity
Console.WriteLine (-1.0 / -0.0); // Infinity
/* ww w.j av a 2 s. co m*/
Dividing zero by zero, or subtracting infinity from infinity, results in a NaN. For example:
Console.WriteLine ( 0.0 / 0.0); // NaN
Console.WriteLine ((1.0 / 0.0) - (1.0 / 0.0)); // NaN
Equality
When using ==
, a NaN
value is never equal to another value, even another NaN
value:
Console.WriteLine (0.0 / 0.0 == double.NaN); // False
To test whether a value is NaN
, you must use the
float.IsNaN
or double.IsNaN
method:
Console.WriteLine (double.IsNaN (0.0 / 0.0)); // True
When using object.Equals, however, two NaN
values are equal:
Console.WriteLine (object.Equals (0.0 / 0.0, double.NaN)); // True