Special Float and Double Values - CSharp Language Basics

CSharp examples for Language Basics:Float

Introduction

floating-point types have values that certain operations treat specially.

These special values are

  • NaN (not a number),
  • +Infinity,
  • -Infinity, and
  • -0.

The float and double classes have constants for NaN, +Infinity, and -Infinity, as well as other values (Max Value, MinValue, and Epsilon).

For example:

Console.WriteLine (double.NegativeInfinity);   // -Infinity

The constants that represent special values for double and float are as follows:

Special value              Double constant                Float constant
NaN                       double.NaN                     float.NaN
+Infinity            double.PositiveInfinity          float.PositiveInfinity
-Infinity            double.NegativeInfinity            float.NegativeInfinity
-0                        -0.0                           -0.0f

Dividing a nonzero number by zero results in an infinite value. For example:

Demo Code

using System;//  w  w  w  .  j  a  v a2 s  .com
class Test
{
   static void Main(){
      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
   }
}

Result

Dividing zero by zero, or subtracting infinity from infinity, results in a NaN. For example:

Demo Code

using System;/* www .ja v a 2  s  .co m*/
class Test
{
static void Main(){
      Console.WriteLine ( 0.0 /  0.0);                  //  NaN
      Console.WriteLine ((1.0 /  0.0) - (1.0 / 0.0));   //  NaN

}
}

Result

When using ==, a NaN value is never equal to another value, even another NaN value:

Demo Code

using System;/*w w w.j  a va2s .c  o  m*/
class Test
{
static void Main(){
      Console.WriteLine (0.0 / 0.0 == double.NaN);    // False
}
}

Result

To test whether a value is NaN, you must use the float.IsNaN or double.IsNaN method:

Demo Code

using System;/* w  ww  .  j a v  a 2 s .  co  m*/
class Test
{
static void Main(){
      Console.WriteLine (double.IsNaN (0.0 / 0.0));   // True
}
}

Result

When using object.Equals, however, two NaN values are equal:

Demo Code

using System;//ww w. j  a  v  a  2s.c om
class Test
{
static void Main(){
      Console.WriteLine (object.Equals (0.0 / 0.0, double.NaN));   // True
}
}

Result


Related Tutorials