C# Numeric Conversions
In this chapter you will learn:
- Integral to integral conversions
- Floating-point to floating-point conversions
- Floating-point to integral conversions
- 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: