可能重复:
How to convert culture specific double using TypeConverter?
我尝试使用Double
将“1.000.000”字符串解析为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: "+"
解析“1.000.000”似乎很好,但它说“1.000.000”不是Double
的有效值。问题是什么?
我试图覆盖Thread.CurrentThread.CurrentCulture
,但它也没有用。
EDITED :::::::::
这似乎也解决了我的问题。 TypeConverter实际上没有ThousandSeperator。我添加了一个它开始工作。
如何使用TypeConverter转换特定于文化的double的可能重复? - Rasmus Faber How to convert culture specific double using TypeConverter?
答案 0 :(得分:2)
试试这个NumberFormatInfo
:
var s = "1.000.000";
var info = new NumberFormatInfo
{
NumberDecimalSeparator = ",",
NumberGroupSeparator = "."
};
var d = Convert.ToDouble(s, info);
您可以将NumberDecimalSeparator
更改为其他内容,只要它与NumberGroupSeparator
不同即可。
编辑:您指定的NumberFormatInfo
也应该有用。
答案 1 :(得分: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);