2015-04-02 25 views
0

我有一種方法,它接受一個字符串值並將其解析爲十進制。這在Windows 8.1上完美的工作,但當我在Windows 7上測試應用程序失敗。 Windows 7確實安裝了Dot net Framework 4.5。在Windows 8上解析字符串爲十進制但在Windows 7上不能解析

可能是什麼問題?

這裏的方法:

void Save_Details() 
{ 
    //The customer enters dots instead of commas to specify a decimal place 
    string Ammount_Now = textbox1.Text.Replace('.', ',');//value text entered is 123.34 
    //The value of Ammount_Now is now 123,34 
    decimal value = 0; 
    bool Ammount_Good = decimal.TryParse(Ammount_Now, out value); 

    if(Ammount_Good) 
    { 
      //continue with method   
      // windows 8 returns true in the decimal.TryParse() 
      // windows 7 returns false in the decimal.TryParse() 
      // They both use .net framework 4.5 
    } 
    else 
    { 
      //failed parsing 
    }  

} 
+1

請不要嘗試「修復」小數,它們是*不*打破。解析時使用適當的文化。在你的情況下InvariantCulture將會起作用。操作系統沒有壞,你只是在不同的區域測試代碼。 – 2015-04-02 11:21:02

+1

檢查兩個操作系統上的小數分隔符是否相同?最可能的一個是逗號,另一個是點。 – Artiom 2015-04-02 11:21:15

回答

1

有什麼錯的操作系統版本,你在不同的語言環境中的機器進行測試的代碼。

只要您在解析時使用正確的CultureInfo,也不需要替換小數點來「修復」它們。如果輸入的文字總是期望使用.作小數點,你應該使用Decimal.TryParse Method (String, NumberStyles, IFormatProvider, Decimal)過載:

decimal.TryParse(Amount_Now,NumberStyles.Number,CultureInfo.InvariantCulture,out value)