2013-01-04 31 views
1

可能重複:
How to convert culture specific double using TypeConverter?1.000.000不是雙C#的有效值

我得到一個異常,而試圖解析 「1,000,000」 的字符串Double通過使用TypeConverter。 我看着System.Globalization.NumberFormatInfo在異常的時刻,它看起來像這樣:

{System.Globalization.NumberFormatInfo} 
    CurrencyDecimalDigits: 2 
    CurrencyDecimalSeparator: "," 
    CurrencyGroupSeparator: "." 
    CurrencyGroupSizes: {int[1]} 
    CurrencyNegativePattern: 8 
    CurrencyPositivePattern: 3 
    CurrencySymbol: "TL" 
    DigitSubstitution: None 
    IsReadOnly: false 
    NaNSymbol: "NaN" 
    NativeDigits: {string[10]} 
    NegativeInfinitySymbol: "-Infinity" 
    NegativeSign: "-" 
    NumberDecimalDigits: 2 
    NumberDecimalSeparator: "," 
    NumberGroupSeparator: "." 
    NumberGroupSizes: {int[1]} 
    NumberNegativePattern: 1 
    PercentDecimalDigits: 2 
    PercentDecimalSeparator: "," 
    PercentGroupSeparator: "." 
    PercentGroupSizes: {int[1]} 
    PercentNegativePattern: 2 
    PercentPositivePattern: 2 
    PercentSymbol: "%" 
    PerMilleSymbol: "‰" 
    PositiveInfinitySymbol: "Infinity" 
    PositiveSign: "+" 

Everyting似乎罰款解析「1000000」,但它說:「1000000」是不是Double的有效值。問題是什麼? 我試圖覆蓋Thread.CurrentThread.CurrentCulture,但它也沒有工作。

EDITED :::::::::

這似乎解決我的問題也是如此。 TypeConverter實際上沒有ThousandSeperator。我加了一個,它開始工作。

可能的重複如何使用TypeConverter轉換文化特定的雙重? - 拉斯穆斯·法伯 How to convert culture specific double using TypeConverter?

+1

一兩句話,以你目前的文化,需要的文化,你用它來解析字符串代碼,你如何看待NumberFormatInfo? –

+0

將其作爲一小段但完整的代碼發佈。 –

+0

其實我在LINQPAD4上做了一個小控制檯應用程序,它確實有效。但它似乎不適用於大型應用程序本身。還有什麼可以看的 –

回答

2

試試這個NumberFormatInfo

var s = "1.000.000"; 
var info = new NumberFormatInfo 
{ 
    NumberDecimalSeparator = ",", 
    NumberGroupSeparator = "." 
}; 
var d = Convert.ToDouble(s, info); 

您可以更改NumberDecimalSeparator別的東西,只要它是從NumberGroupSeparator不同。

編輯:你指定的NumberFormatInfo也應該工作。

1

Most normal numerical types have parse methods. Use TryParse if you're unsure if it's valid (Trying to parse "xyz" as a number will throw an exception)

For custom parsing you can define a NumberFormatInfo like this:

var strInput = "1.000.000"; 
var numberFormatInfo = new NumberFormatInfo 
{ 
    NumberDecimalSeparator = ",", 
    NumberGroupSeparator = "." 
}; 
double dbl = Double.Parse(strInput, numberFormatInfo); 

這個解決方案也將工作

var format = new System.Globalization.NumberFormatInfo(); 
format.NumberDecimalSeparator = ","; 
format.NumberGroupSeparator = "."; 
double dbl2 = Double.Parse("1.000.000", format);