Input string was not in a correct format

后端 未结 8 1178
滥情空心
滥情空心 2020-11-22 02:55

I\'m new with C#, I have some basic knowledge in Java but I can\'t get this code to run properly.

It\'s just a basic calculator, but when I run the program VS2008 gi

相关标签:
8条回答
  • 2020-11-22 03:12

    I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.

    I'd declared a string and was formatting it for use with JQTree which requires curly braces ({}). You have to use doubled curly braces for it to be accepted as a properly formatted string:

    string measurements = string.empty;
    measurements += string.Format(@"
        {{label: 'Measurement Name: {0}',
            children: [
                {{label: 'Measured Value: {1}'}},
                {{label: 'Min: {2}'}},
                {{label: 'Max: {3}'}},
                {{label: 'Measured String: {4}'}},
                {{label: 'Expected String: {5}'}},
            ]
        }},",
        drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
        drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
        drv["Min"] == null ? "NULL" : drv["Min"],
        drv["Max"] == null ? "NULL" : drv["Max"],
        drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
        drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);
    

    Hopefully this will help other folks who find this question but aren't parsing numerical data.

    0 讨论(0)
  • 2020-11-22 03:14

    If you are not validating explicitly for numbers in the text field, in any case its better to use

    int result=0;
    if(int.TryParse(textBox1.Text,out result))
    

    Now if the result is success then you can proceed with your calculations.

    0 讨论(0)
  • 2020-11-22 03:16

    I had a similar problem that I solved with the following technique:

    The exception was thrown at the following line of code (see the text decorated with ** below):

    static void Main(string[] args)
        {
    
            double number = 0;
            string numberStr = string.Format("{0:C2}", 100);
    
            **number = Double.Parse(numberStr);**
    
            Console.WriteLine("The number is {0}", number);
        }
    

    After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:

    number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number
    

    At that point the Parse(...) method worked as expected.

    0 讨论(0)
  • 2020-11-22 03:20

    In my case I forgot to put double curly brace to escape. {{myobject}}

    0 讨论(0)
  • 2020-11-22 03:23

    Problems

    There are some possible cases why the error occurs:

    1. Because textBox1.Text contains only number, but the number is too big/too small

    2. Because textBox1.Text contains:

      • a) non-number (except space in the beginning/end, - in the beginning) and/or
      • b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or
      • c) decimal separator (which should not exist in int parsing)

    NOT OK Examples:

    Case 1

    a = Int32.Parse("5000000000"); //5 billions, too large
    b = Int32.Parse("-5000000000"); //-5 billions, too small
    //The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647
    

    Case 2 a)

    a = Int32.Parse("a189"); //having a 
    a = Int32.Parse("1-89"); //having - but not in the beginning
    a = Int32.Parse("18 9"); //having space, but not in the beginning or end
    

    Case 2 b)

    NumberStyles styles = NumberStyles.AllowThousands;
    a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
    b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator
    

    Case 2 c)

    NumberStyles styles = NumberStyles.AllowDecimalPoint;
    a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!
    

    Seemingly NOT OK, but actually OK Examples:

    Case 2 a) OK

    a = Int32.Parse("-189"); //having - but in the beginning
    b = Int32.Parse(" 189 "); //having space, but in the beginning or end
    

    Case 2 b) OK

    NumberStyles styles = NumberStyles.AllowThousands;
    a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
    b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture
    

    Solutions

    In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:

    1234
    

    Also, you may consider of

    1. using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.
    2. check the result of TryParse and handle it if not true

      int val;
      bool result = int.TryParse(textbox1.Text, out val);
      if (!result)
          return; //something has gone wrong
      //OK, continue using val
      
    0 讨论(0)
  • 2020-11-22 03:25

    it was my problem too .. in my case i changed the PERSIAN number to LATIN number and it worked. AND also trime your string before converting.

    PersianCalendar pc = new PersianCalendar();
    char[] seperator ={'/'};
    string[] date = txtSaleDate.Text.Split(seperator);
    int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());
    
    0 讨论(0)
提交回复
热议问题