
You are interested in how floating point values are casted to ints in the C# programming language. Also, you want to find out the result of a conversion to an integer from a value that cannot fit in an integer. We demonstrate various conversions from double, long, and ulong to int.
Expression and result table (int)1.1 = 1 (int)1.5 = 1 (int)1.99 = 1 (int)-1.1 = -1

First, when you cast doubles to ints, the values after the decimal place will be dropped in the resulting value. This is demonstrated with the values 1.1, 1.5, 1.99, and -1.1. Next, you get an unusable result when you cast long and ulong values that cannot fit in an int. Finally, very large negative and positive doubles are casted to the same value, which is unusable.
This C# program shows how to cast ints using the explicit syntax form.
Program that uses (int) casts [C#]
class Program
{
static void Main()
{
{
double value1 = 1.1;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
{
double value1 = 1.5;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
{
double value1 = 1.99;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
{
double value1 = -1.1;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
{
long value1 = 10000000000;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
{
ulong value1 = 10000000000;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
{
double value1 = 10000000000;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
{
double value1 = -10000000000;
int value2 = (int)value1;
System.Console.WriteLine("{0} -> {1}", value1, value2);
}
}
}
Output
1.1 -> 1
1.5 -> 1
1.99 -> 1
-1.1 -> -1
10000000000 -> 1410065408
10000000000 -> 1410065408
10000000000 -> -2147483648
-10000000000 -> -2147483648
This is important because if you ever cast fractional values to integers, you will know they are always rounded down to the nearest integer. This means even the value 1.99 is changed to 1; the (int) cast never rounds the value up.
Also, when you cast longs, ulongs, or doubles that cannot be represented in the memory space of an int, you will receive predictable but unusable results. If you want to be alerted if such an error occurs, use the checked context; also note the unchecked context to disable this.
Checked Context Unchecked Context
The (int) cast in C# programs is very useful when converting from a double or other floating point value to an integer, but it never rounds up. This may be acceptable, but may also be problematic. For more sophisticated rounding, check out the Math.Round method in the System namespace.
Math.Round Method Cast Examples