当我想将字符串格式的负数转换为 Double 时,ToDouble 总是抛出异常

ToDouble always throws an exception when i want to convert a negative number in string format to Double

当我运行以下代码时它总是抛出异常

string a = "-12.12";
double b = Convert.ToDouble(a);

An exception of type 'System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code

代码有什么问题?

我强烈怀疑您 运行 在使用 , 作为小数点分隔符的语言环境中...或者使用不同的符号表示否定。您可以传入一个 CultureInfo 来指定如何解析 - 我通常使用 double.Parse 而不是 Convert.ToDouble:

double x = double.Parse(a, CultureInfo.InvariantCulture);

那绝对没问题。如果它仍然不起作用,则表明您的 actual 字符串不完全是“-12.12”。例如,如果“-”实际上是破折号或类似的东西,它将无法正确解析。