Cast. 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).
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.
Rounding. 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
Checked context. 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.
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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 21, 2024 (new example).