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 constantFloat constant
double.NaNfloat.NaN
double.PositiveInfinityfloat.PositiveInfinity
double.NegativeInfinityfloat.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 





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var