在全局线程中更改NumberFormat分隔符后,Decimal Parse抛出异常

时间:2014-02-19 17:16:20

标签: c# globalization cultureinfo number-formatting currentculture

   I have changed Global Application Culture thread for currency number format in (fr-CA) as shown below. 

Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyPositivePattern = 1;
                                Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencyNegativePattern = 5;

                            CultureInfo CADCultureref = new CultureInfo("fr-CA");
                            CADCultureref = Thread.CurrentThread.CurrentCulture;
                            NumberFormatInfo CADNumFormatref = new NumberFormatInfo();
                            CADNumFormatref = Thread.CurrentThread.CurrentCulture.NumberFormat;

                            CADNumFormatref.CurrencyGroupSeparator = ".";
                            CADNumFormatref.CurrencyDecimalSeparator = ",";
                            CADCultureref.NumberFormat = CADNumFormatref;
                            Thread.CurrentThread.CurrentCulture = CADCultureref;
                            Thread.CurrentThread.CurrentUICulture = CADCultureref;

然后我尝试从货币解析值,如下所示:

Decimal digit = 1000000;
String currency = digit.ToString("C"); //  1.000.000,00$ (fr-CAD)
decimal parseValue = decimal.Parse(currency , System.Globalization.NumberStyles.Currency | System.Globalization.NumberStyles.Number); 

我在解析值时遇到异常“{输入字符串格式不正确}。”

由于在CurrentThread的Numberformatinfo中更改了组分隔符和小数分隔符,无法解析。

我需要显示“,”代替“。”和“。”代替“,”。

1 个答案:

答案 0 :(得分:1)

不清楚您的问题是什么,但通常最好将文化信息/数字格式明确传递给格式化和解析函数,如:

var  numberFormat = new CultureInfo( "en-US", false ).NumberFormat;
numberFormat.CurrencyDecimalSeparator  = ",";
numberFormat.CurrencyGroupSeparator  = ".";
Console.WriteLine(400000.ToString("C", numberFormat)); // Output: $ 4.000,00   
Console.WriteLine(
    decimal.Parse(400000.ToString("C", numberFormat),
           NumberStyles.Currency | NumberStyles.Number, 
           numberFormat));