C# Numeric Conversions

In this chapter you will learn:

  1. Integral to integral conversions
  2. Floating-point to floating-point conversions
  3. Floating-point to integral conversions
  4. Decimal conversions

Integral to integral conversions

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

Otherwise, an explicit conversion is required. For example:


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

Floating-point to floating-point conversions

A float can be implicitly converted to a double, since a double can represent every possible value of a float. The reverse conversion must be explicit.


float f = 0.2F;
double d = f;

f = (float)d;

Floating-point to integral conversions

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


int i = 1;
float f = i;

The reverse conversion must be explicit:


int i2 = (int)f;

Decimal conversions

All integral types can be implicitly converted to the decimal type, since a decimal can represent every possible C# integral value. All other numeric conversions to and from a decimal type must be explicit.


int i = 1;
decimal d = i;

i = (decimal)d;

Next chapter...

What you will learn in the next chapter:

  1. What is C# Bool Type
  2. How to create bool type variable
  3. if statement with bool variable
Home »
  C# Tutorial »
    C# Language »
      C# Data Types
C# Predefined Type Taxonomy
C# Numeric Types
C# Numeric Literals
C# Numeric suffixes
C# float and double
C# Float and Double Special Values
C# decimal
C# Numeric Conversions
C# Bool Type
C# char type
C# String Type