Trying to set the decimal separator for the current language, getting "Instance read only"

I have a code that was originally written for the English market, where the decimal separator is "." . therefore, it expects numeric values ​​as strings to use "." as a separator. But now we have users in other places, for example, in Europe, where the decimal separator is ",".

So, in the context of my software (really only the current thread) I want to redefine the decimal separator for the current language as "." even if it uses something else by default.

I tried

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

But I get the exception " Instance is only-only " in the third line. NumberFormatInfo is apparently not writable. So how do you set an existing decimal separator in a language other than its default value?

+5
c # localization
source share
2 answers

You need to create a new culture, and you can use the current culture as a template and just change the delimiter. Then you must set the current culture to your new one, since you cannot directly change the property in the current culture.

 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; } 
+11
source share

You can use the Clone() method on NumberFormatInfo , which will create a mutable version (i.e. IsReadOnly = false). Then you can set the currency symbol and / or other parameters of the number format:

 string sep = "."; NumberFormatInfo nfi1 = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); nfi1.NumberDecimalSeparator = sep; 
+1
source share

All Articles