C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Expression and result table:
(int)1.1 = 1
(int)1.5 = 1
(int)1.99 = 1
(int)-1.1 = -1
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.
LongDoubleC# 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
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.
CheckedTip: For more sophisticated rounding, check out the Math.Round method in the System namespace.
Math.Round