Question

I tracked down a bug in my application that occurred for people in countries where the default decimal symbol was a comma instead of a period. Is there any way in C# to set the decimal symbol for my application without affecting other apps or permanently changing the system settings? I tried this but it says the NumberDecimalSeparator is readonly.

Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
Was it helpful?

Solution

I you still need to do that you can change the CurrentCulture on the thread like so:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-Us");

Chooe a Culture that has the decimal properties you need.

var numpre = 1.1.ToString();
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-Us");
var numpost = 1.1.ToString();
numpre.Dump();
numpost.Dump();

Output:

1,1
1.1

OTHER TIPS

Depending on the situation, the right thing to do may not be to try to enforce a format, but to make your application aware of the locale and take it into account. Which is something really easy to do since .NET has it all implemented already (otherwise it would be a nightmare).

I'd say there are two cases to treat: when data can be passed from one machine to another (some stored data, a file, a script, etc.), and when it is not supposed to (a visual feedback, a value field, etc.).

When it's about data that can be passed from one machine to another, you have to choose a format that is culture agnostic. This will guarantee the machines use the same format and interpret a given data the same way regardless of the machine user settings. That's what programming languages do, and seems to be your case.

The .NET library provides CultureInfo.InvariantCulture for this:

double x = 0.0;
double.TryParse(source, NumberStyles.Float, CultureInfo.InvariantCulture, out x);
string str = x.ToString(CultureInfo.InvariantCulture);

When it's about local information, you should read and write in the language of the user, using his locale to parse numbers in inputs (text fields) and format them in outputs. This tends to be neglected, but I think it is a very important point, as a number like 1,234.567 will have a radically different meaning depending on the culture. See for example how a software like Microsoft Excel will represent and let you enter numbers differently depending on your environment settings.

In this case the above code snippet would become:

double x = 0.0;
double.TryParse(source, NumberStyles.Float, CultureInfo.CurrentUICulture, out x);
string str = x.ToString(CultureInfo.CurrentUICulture);

See more on the MSDN documentation: http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top