问题描述
我有一些代码最初是为英语市场编写的,其中小数点分隔符为."因此,它期望数值作为字符串使用.".作为分隔符.但是我们现在在其他地方有用户,例如在欧洲的小数点分隔符为,"的地方.
I have code that was originally written for an English language market where the decimal separator is "." so it's expecting numeric values as strings to use "." as the separator. But we now have users in other places, e.g., places in Europe where the decimal separator is ",".
因此,在我的软件环境中(实际上只是当前线程),我想覆盖当前语言为."的小数点分隔符.即使默认为其他内容.
So, in the context of my software (really just the current thread) I want to override the decimal separator for the current language to be "." even if it defaults to something else.
我尝试过
String sep = ".";
NumberFormatInfo nfi1 = NumberFormatInfo.CurrentInfo;
nfi1.NumberDecimalSeparator = sep;
但是第三行出现"实例为只读"异常.显然NumberFormatInfo是不可写的.那么,如何将当前语言的小数点分隔符设置为默认语言以外的其他内容?
But I get an "Instance is read-only" exception on the third line. Apparently NumberFormatInfo is not writable. So how DO you set the current language's decimal separator to something other than its default?
推荐答案
您需要创建新的区域性,并且可以将当前区域性用作模板,而仅更改分隔符.然后,您必须将当前区域性设置为新创建的区域性,因为您不能直接更改当前区域性中的属性.
You need to create a new culture and you can use the current culture as a template and only change the separator.Then you must set the current culture to your newly created one as you cannot change the property within current culture directly.
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;
}
这篇关于尝试为当前语言设置小数点分隔符,获取“实例只读".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!