12

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 convert function, rather than:

double d = 3.1415;
int i = (int)d;

which has an implicit floor and convert.

Also, more concerning, I noticed in some production code I was reading:

double d = 3.1415;
float f = Convert.ToSingle(d);

Is that the same as:

float f = (float)d;

Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.

Wyzfen
  • 363
  • 3
  • 9

4 Answers4

12

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.

Michael L Perry
  • 7,327
  • 3
  • 35
  • 34
3

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.

Mark T
  • 3,464
  • 5
  • 31
  • 45
1

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.

NotDan
  • 31,709
  • 36
  • 116
  • 156
  • Doesn't 'Int32.Parse(String) : Int32' actually convert a string to an int? – Anthony Mastrean Sep 19 '08 at 18:18
  • Int32.Parse will convert a "numeric" string into an int and it will throw an exception if the conversion fails. Int32.TryParse will return false if the conversion fails while Convert.ToInt32 will return 0 if the conversion fails. – Rune Grimstad Oct 29 '08 at 14:14
1

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.

ddc0660
  • 4,022
  • 2
  • 21
  • 30