CSharp - Data Types Numeric Conversions

Introduction

Converting between integral types

Integral type conversions are implicit if the destination type can represent every possible value of the source type.

Otherwise, an explicit conversion is required.

For example:

int x = 1;           // int is a 32-bit integer
long y = x;          // Implicit conversion to 64-bit integral type
short z = (short)x;  // Explicit conversion to 16-bit integral type

Converting between floating-point types

A double can represent every possible value of a float.

A float point value can be implicitly converted to a double.

Assign double type to float type must be explicit.

Converting between floating-point and integral types

All integral types may be implicitly converted to all floating-point types:

int i = 1;
float f = i;

The reverse conversion must be explicit:

int i2 = (int)f;

Note

During casting from a floating-point number to an integral type, fractional portion is truncated and no rounding is performed.

System.Convert has methods to round floating point values while converting between various numeric types.

Implicitly converting a integral type to a floating-point type preserves magnitude but may occasionally lose precision.

Demo

using System;
class MainClass/* w ww. j  a  va2 s . c o  m*/
{
   public static void Main(string[] args)
   {
       int i1 = 100000001;
       float f = i1;          // Magnitude preserved, precision lost
       int i2 = (int)f;    

       Console.WriteLine(i1);
       Console.WriteLine(f);
       Console.WriteLine(i2);

   }
}

Result

Decimal conversions

A decimal value can represent every possible integral-type value in C#.

All integral types can be implicitly converted to the decimal type.

All other numeric conversions to and from a decimal type must be explicit.

Related Topics