How do I convert a decimal to an int?
int i = (int)d;
will give you the number rounded down.
If you want to round to the nearest even number (i.e. >.5 will round up) you can use
int i = (int)Math.Round(d, MidpointRounding.ToEven);
In general you can cast between all the numerical types in C#. If there is no information that will be lost during the cast you can do it implicitly:
int i = 10;
decimal d = i;
though you can still do it explicitly if you wish:
int i = 10;
decimal d = (decimal)i;
However, if you are going to be losing information through the cast you must do it explicitly (to show you are aware you may be losing information):
decimal d = 10.5M;
int i = (int)d;
Here you are losing the ".5". This may be fine, but you must be explicit about it and make an explicit cast to show you know you may be losing the information.
No answer seems to deal with the OverflowException/UnderflowException that comes from trying to convert a decimal that is outside the range of int.
int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));
This solution will return the maximum or minimum int value possible if the decimal value is outside the int range. You might want to add some rounding with Math.Round, Math.Ceiling or Math.Floor for when the value is inside the int range.
I prefer using Math.Round, Math.Floor, Math.Ceiling or Math.Truncate to explicitly set the rounding mode as appropriate.
Note that they all return Decimal as well - since Decimal has a larger range of values than an Int32, so you'll still need to cast (and check for overflow/underflow).
checked {
int i = (int)Math.Floor(d);
}
I find that the casting operator does not work if you have a boxed decimal (i.e. a decimal value inside an object type). Convert.ToInt32(decimal as object) works fine in this case.
This situation comes up when retrieving IDENTITY/AUTONUMBER values from the database:
SqlCommand foo = new SqlCommand("INSERT INTO...; SELECT SCOPE_IDENTITY()", conn);
int ID = Convert.ToInt32(foo.ExecuteScalar()); // works
int ID = (int)foo.ExecuteScalar(); // throws InvalidCastException
See 4.3.2 Unboxing conversions
decimal d = 2;
int i = (int) d;
This should work just fine.
decimal vIn = 0.0M;
int vOut = Convert.ToInt32(vIn);
Here is a very handy convert data type webpage for those of others. http://www.convertdatatypes.com/Convert-decimal-to-int-in-CSharp.html