Cast int. 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.
Conversion info. 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).
Some input and output. 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.
Example program. We perform many casts, and each is described in a separate section of the text. Casting some values can result in unexpected behavior.
Part 1 When you convert doubles to ints, the values after the decimal place will be dropped in the resulting value.
Part 2 You get an unusable result when you cast long and ulong values that cannot fit in an int.
Discussion. 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.
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.
A summary. The (int) cast is useful when converting from a double or other floating point value to an integer. A positive integer is never rounds up—this is sometimes problematic.
Final note. For more sophisticated rounding, check out the Math.Round method in the System namespace. Casting to ints can be useful, but care must be used.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.