Input string was not in a correct format #2

后端 未结 10 1224
一向
一向 2020-12-03 21:24
double temp;
temp = (double)Convert.ToDouble(\"1234.5678\");

Hey Lads and Ladies, I can\'t for the life of me figure out why the above line isn\'t

相关标签:
10条回答
  • 2020-12-03 21:43

    first solution (as mentioned in other posts):

    double temp = double.Parse("1234.5678", CultureInfo.InvariantCulture);
    

    second solution - make it default to current thread:

    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    double temp = double.Parse("1234.5678");
    

    third solution - make it default to block of code:

    var prevCurrentCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    ...
    double temp = double.Parse("1234.5678");
    ...
    Thread.CurrentThread.CurrentCulture = prevCurrentCulture;
    
    0 讨论(0)
  • 2020-12-03 21:44
    double temp = double.Parse("1234,5678");
    
    0 讨论(0)
  • 2020-12-03 21:45

    I found the problem when you let the text box empty then this error occurs so try this one to handle it.

    An unhandled exception of type System.FormatException occurred in mscorlib.dll Additional information: Input string was not in a correct format.

    if (!string.IsNullOrEmpty(Txt1.Text)) {int _qty = (int)Convert.ToInt32(Txt1.Text);}
    
    0 讨论(0)
  • 2020-12-03 21:54

    As far as I know the Convert methods use the current locale to do such conversions. In this case I'd guess your current locale would expect a comma as decimal point. Try to set the current locale for your application or the conversion to some language/country where dots are used (e.g. en_US). The method should provide a second optional parameter to provide a IFormatProvider as an alternative solution.

    0 讨论(0)
  • 2020-12-03 21:57

    I don't see any problem with the above code.it works fine and prints the value 1234.5678. I have tried it in VS2008. Probably, something to do with locale settings on your machine.

    0 讨论(0)
  • 2020-12-03 22:00

    In order to convert string to double without an exception:

    An unhandled exception of type System.FormatException occurred in mscorlib.dll

    Additional information: Input string was not in a correct format.

    make it culture-insensitive by providing second parameter value CultureInfo.InvariantCulture, for example:

    double.Parse("1234.5678", CultureInfo.InvariantCulture) 
    
    0 讨论(0)
提交回复
热议问题