TheDeveloperBlog.com


C# Cast to Int

Cast, Int. Floating point values can be cast to ints. This has predictable results. We find out the result of a conversion to an integer from a value that cannot fit in an integer. We show conversions from double, long and ulong to int.

Int
Expression and result table

(int)1.1   =  1
(int)1.5   =  1
(int)1.99  =  1
(int)-1.1  = -1


Example. First, when you cast doubles to ints, the values after the decimal place will be dropped in the resulting value. This is similar to Math.Floor in this aspect. This is demonstrated with four double values.

Math.Floor

Next, you get an unusable result when you cast long and ulong values that cannot fit in an int. Finally, large negative and positive doubles are cast to the same value, which is unusable.

LongUlongDouble
C# program that uses int casts

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


Discussion. 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 we cast longs, ulongs or doubles that cannot fit in the memory space of an int, we receive predictable but unusable results.

Tip: If you want to be alerted if such an error occurs, use the checked context. Also note the unchecked context to disable this.

CheckedUnchecked

Summary. The (int) cast in C# programs is 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.

Tip: For more sophisticated rounding, check out the Math.Round method in the System namespace.

Math.Round