System.Convert.ToInt vs (int)

前端 未结 4 1647
猫巷女王i
猫巷女王i 2020-12-18 22:38

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

相关标签:
4条回答
  • 2020-12-18 23:19

    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.

    0 讨论(0)
  • 2020-12-18 23:22

    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.

    0 讨论(0)
  • 2020-12-18 23:28

    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.

    0 讨论(0)
  • 2020-12-18 23:36

    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.

    0 讨论(0)
提交回复
热议问题