Input string was not in a correct format #2

2019-01-12 06:08发布

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 working. The above line gives me a runtime error that says;

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

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

10条回答
Fickle 薄情
2楼-- · 2019-01-12 06:15

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) 
查看更多
聊天终结者
3楼-- · 2019-01-12 06:16

I recommend you use TryParse instead, so you don't need to handle parsing exceptions.

double temp = 0;
if (double.TryParse("123.456", out temp)
{
    Console.WriteLine(string.Format("Parsed temp: {0}", temp);
}
else
{
    Console.WriteLine("Input value was not able to be parsed.");
}
查看更多
Summer. ? 凉城
4楼-- · 2019-01-12 06:21
double temp = double.Parse("1234,5678");
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-12 06:22

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.

查看更多
做个烂人
6楼-- · 2019-01-12 06:27

You may be somehow using a european local. In some countries the . and , in numbers is reversed.

查看更多
做个烂人
7楼-- · 2019-01-12 06:27

Check your regional settings. Your decimal symbol needs to be ".".

查看更多
登录 后发表回答