這可能是因爲您使用了錯誤的逗號分隔符號,甚至在指定double值時發生了其他錯誤。 無論如何,在這種情況下,您必須使用Double.TryParse()方法,該方法在異常方面是安全的,並允許指定格式提供者,基本上使用文化。
public static bool TryParse(
string s,
NumberStyles style,
IFormatProvider provider,
out double result
)
The TryParse method is like the Parse(String, NumberStyles, IFormatProvider) method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero.
編輯:回答評論
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))
來源
2011-09-23 17:38:30
sll
你輸入什麼樣的價值觀? –
值在0-10像4.5或5.5 –