CSharp examples for Language Basics:Float
floating-point types have values that certain operations treat specially.
These special values are
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:
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 } }
Dividing zero by zero, or subtracting infinity from infinity, results in a NaN. For example:
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 } }
When using ==, a NaN value is never equal to another value, even another NaN value:
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 } }
To test whether a value is NaN, you must use the float.IsNaN or double.IsNaN method:
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 } }
When using object.Equals, however, two NaN values are equal:
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 } }