Format exception when I am converting to Int32

前端 未结 5 1364
深忆病人
深忆病人 2020-12-22 15:32

While i am trying to convert a value to Int32, I get an error format exception, meaning the value is not in the proper format. I think I am converting a value in right forma

相关标签:
5条回答
  • 2020-12-22 15:49

    You will get FormatException in cases such next:

    Convert.ToInt32("foo");
    Convert.ToInt32(5.5);
    

    because

    FormatException

    value does not consist of an optional sign followed by a sequence of digits (0 through 9).

    MSDN

    0 讨论(0)
  • 2020-12-22 15:57

    You can always check the type of the value you are passing in to such functions by using the GetType().

    The condition where I was stuck in this issue was conversion of a dynamically generated stringyfied decimal value to int. Figured out the type of the value using the GetType() and first converting it into double then int solved the problem.

    0 讨论(0)
  • 2020-12-22 15:58

    Perhaps the hint is in "I think I am converting a value in right format though"

    Are you sure your number is formatted according to your current culture?

    If not, it's Int32.TryParse(String, NumberStyles, IFormatProvider, Int32%) [details here][1] that you should be using

    [1]: http://Int32.TryParse Method (String, NumberStyles, IFormatProvider, Int32%)

    0 讨论(0)
  • 2020-12-22 15:59

    Try using Int32.TryParse() you can find documentation on MSDN

    0 讨论(0)
  • 2020-12-22 16:02
    string str = "123";
    int i = 0;
    if (int.TryParse(str, out i))
    {
        //do your logic here
    }
    

    Share your code here, you might missed something

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