System.FormatException:输入字符串的格式不正确

private void ReadUnitPrice() { Console.Write("Enter the unit gross price: "); unitPrice = double.Parse(Console.ReadLine()); } 

这应该有用,但我遗漏了一些明显的东西。 每当我输入一个double时它就会给出错误:System.FormatException:输入字符串的格式不正确。 请注意,’unitPrice’被声明为double。

可能是您使用了错误的逗号分隔符号,甚至在指定double值时发出了其他错误。 无论如何在这种情况下你必须使用Double.TryParse()方法,这在exception方面是安全的,并且允许指定格式提供者,基本上使用文化。

 public static bool TryParse( string s, NumberStyles style, IFormatProvider provider, out double result ) 

TryParse方法类似于Parse(String,NumberStyles,IFormatProvider)方法,但如果转换失败,此方法不会引发exception。 如果转换成功,则返回值为true,并将result参数设置为转换结果。 如果转换失败,则返回值为false,结果参数设置为零。

编辑:回答评论

 if(!double.TryParse(Console.ReadLine(), out unitPrice)) { // parse error }else { // all is ok, unitPrice contains valid double value } 

你也可以尝试:

 double.TryParse(Console.ReadLine(), NumberStyle.Float, CultureInfo.CurrentCulture, out unitPrice))