2011-09-23 15 views
5
private void ReadUnitPrice() 
    { 
     Console.Write("Enter the unit gross price: "); 
     unitPrice = double.Parse(Console.ReadLine()); 
    } 

這應該可行,但我錯過了一些明顯的東西。每當我輸入一個double它給我的錯誤:System.FormatException:輸入字符串不是在一個正確的格式。 請注意'unitPrice'被聲明爲double。System.FormatException:輸入字符串的格式不正確

+0

你輸入什麼樣的價值觀? –

+0

值在0-10像4.5或5.5 –

回答

6

這可能是因爲您使用了錯誤的逗號分隔符號,甚至在指定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)) 
+0

是的,我只是試過,其實..並猜測是什麼,它的工作原理。我討厭瑞典的逗號分隔符號。 –

+0

TryParse在它的參數中需要更多的參數,並且因爲我是C#中的新手,並且不太瞭解TryParse的位置,然後發送結果(因爲它返回一個布爾值)現在解析。 「接收2個返回值」似乎有點凌駕於我的頭上,但我會將TryParse記住以備將來使用。謝謝。 –

+0

@ Ryuji89:看到更新的答案,編輯部分 – sll