In C# 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
. Casting a floating-point number removes the fractional part—so it rounds down (when positive).
Consider a double
value with a fractional part, like 1.1. When we cast it, we expect to receive an integer equal to 1. Even 1.99 should result in 1.
(int)1.1 = 1 (int)1.5 = 1 (int)1.99 = 1 (int)-1.1 = -1
We perform many casts, and each is described in a separate section of the text. Casting some values can result in unexpected behavior.
ulong
values that cannot fit in an int
.// Part 1: cast 4 double values. { 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); } // Part 2: cast long values. { 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); } // Part 3: cast large double values. { 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); }1.1 -> 1 1.5 -> 1 1.99 -> 1 -1.1 -> -1 10000000000 -> 1410065408 10000000000 -> 1410065408 10000000000 -> -2147483648 -10000000000 -> -2147483648
For more sophisticated rounding, check out the Math.Round
method in the System
namespace. We can call Math.Round
, and then once the value is rounded as desired, cast to int
.
using System; double value1 = 1.5; // Use int cast. int value2 = (int)value1; // Use Math.Round, then cast to int. int value3 = (int)Math.Round(value1); Console.WriteLine($"{value1} -> {value2} ... {value3}");1.5 -> 1 ... 2
When we cast longs, ulongs or doubles that cannot fit in the memory space of an int
, we receive predictable but unusable results.
using System; // This cast will return an invalid result. double value = double.MaxValue; int result = (int)value; Console.WriteLine(result); checked { double value2 = double.MaxValue; // This will throw an exception. int result2 = (int)value2; }-2147483648 Unhandled exception. System.OverflowException: Arithmetic operation resulted in an overflow. at ...\Program.cs:line 12
Casting to int
is often done in C#. When we cast positive fractional values, they are rounded down to the nearest integer. This means even the value 1.99 is changed to 1.