CSharp/C# Tutorial - C# Numeric Value

8- and 16-Bit Integrals

The 8- and 16-bit integral types are byte, sbyte, short, and ushort.

C# implicitly converts them to larger types as required.

This can cause a compile-time error when trying to assign the result back to a small integral type:

short x = 1, y = 1; 
short z = x + y; // Compile-time error 

x and y are implicitly converted to int so that the addition can be performed.

The result is also an int, which cannot be implicitly cast back to a short.

To make this compile, we must add an explicit cast:

short z = (short) (x + y);

Special Float and Double Values

The 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 such as MaxValue, MinValue, and Epsilon.

For example:

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

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

Special valueDouble constantFloat constant

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 

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 

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 

double Versus decimal

double is useful for scientific computations. decimal is useful for financial computations.