I noticed in another post, someone had done something like:
double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));
Why did they use the
You can use Convert when you have a string that you want to convert to an int
int i = Convert.ToInt32("1234");
Convert and casting will both throw an exception if they fail.
i.e, this will still throw an exception, it will not return 0:
Convert.ToInt32("1234NonNumber");
In many cases Convert and casting will have the same result, but a cast is often times easier to read.
Casting to int is implicit truncation, not implicit flooring:
double d = -3.14;
int i = (int)d;
// i == -3
I choose Math.Floor or Math.Round to make my intentions more explicit.
Convert.ToInt32() is used on strings (http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx) while casting can only be used on types that have internal converters (numeric types). The real trick comes in deciding between Int32.Parse and Convert.ToInt32(). Convert.ToInt32() is tolerant of a null parameter and returns 0 while Int32.Parse() will throw an ArgumentNullException.
Rounding is also handled differently:
x=-2.5 (int)x=-2 Convert.ToInt32(x)=-2
x=-1.5 (int)x=-1 Convert.ToInt32(x)=-2
x=-0.5 (int)x= 0 Convert.ToInt32(x)= 0
x= 0.5 (int)x= 0 Convert.ToInt32(x)= 0
x= 1.5 (int)x= 1 Convert.ToInt32(x)= 2
x= 2.5 (int)x= 2 Convert.ToInt32(x)= 2
Notice the x=-1.5 and x=1.5 cases.
In some algorithms, the rounding method used is critical to getting the right answer.