CultureInfo and Double.parse and double.toString not worked correctly

为君一笑 提交于 2020-01-07 04:20:28

问题


How can I force c# application to use . for decimal separator and ignore culture settings in server. I have this problem with double.ToString and double.parse I should change setting in application level because of large scale of application.

exception occurse in case like double.parse("1/25") and 1.25 ToString

I have Try This code

string CultureName = Thread.CurrentThread.CurrentCulture.Name;
        CultureInfo ci = new CultureInfo(CultureName);
        if (ci.NumberFormat.NumberDecimalSeparator != ".")
        {
            // Forcing use of decimal separator for numerical values
            ci.NumberFormat.NumberDecimalSeparator = ".";
            Thread.CurrentThread.CurrentCulture = ci;
        }

in app_start begin request and method that change culture but can't solve problem

The application was working correctly in .net 3.5 but after upgrade to .net 4.6.2 this problems happened on server 2012 and windows 10.


回答1:


The direct way is to specify the CultureInfo.InvariantCulture:

 string source = "1.234";

 double result = double.Parse(source, CultureInfo.InvariantCulture);

The by-way is to assign CultureInfo.InvariantCulture as the current culture

var saved = Thread.CurrentThread.CurrentCulture;

try {
  Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

  ...

  double result = double.Parse(source);

  ... 
}
finally {
  Thread.CurrentThread.CurrentCulture = saved;
}

Finally, you may want to modify the existing current culture (kind of fixing "at application level"):

CultureInfo modified = CultureInfo.CurrentCulture.Clone() as CultureInfo;

modified.NumberFormat.NumberDecimalSeparator = ".";

// Business as usual except the decimal separator which is now dot '.' 
Thread.CurrentThread.CurrentCulture = modified;

...

double result = double.Parse(source);



回答2:


I defined a method and use it in every where in application that changes cultureinfo

public static void CorrectNumberFormat()
    {
        var culture = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
        if (culture.NumberFormat.NumberDecimalSeparator != ".")
        {
            culture.NumberFormat.NumberDecimalSeparator = ".";
            culture.NumberFormat.CurrencyDecimalSeparator = ".";
            culture.NumberFormat.PercentDecimalSeparator = ".";
            CultureInfo.DefaultThreadCurrentCulture = culture;
            CultureInfo.DefaultThreadCurrentUICulture = culture;

            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }
    }


来源:https://stackoverflow.com/questions/44879066/cultureinfo-and-double-parse-and-double-tostring-not-worked-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!