Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

c# - Trying to set the decimal separator for the current language, getting "Instance is read Only"

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.

I tried

  String sep = "."; 
  NumberFormatInfo nfi1 = NumberFormatInfo.CurrentInfo;
  nfi1.NumberDecimalSeparator = sep;

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...