AdSense

Wednesday 19 June 2013

C# - dot or comma problem

(Deutsche Version) In C, it was very simple: Every number has to be put in with a dot. Every programmer was aware of this. Sadly, C# thinks to be intelligent and (depending of the region) accepts a comma instead of a dot. On my german computer it looks like this:

string stringGerman = "3,1415926";
string stringEnglish = "3.1415926";
double doubleGerman = Convert.ToDouble(stringGerman);
double doubleEnglish = Convert.ToDouble(stringEnglish);
System.Console.Write("{0} - {1}\n", doubleGerman, doubleEnglish);


The output is: 3,1415926 - 31415926, C# does not accept the dot. This can cause a lot of confusion because nearly every programmer enters numbers with a dot and not a comma. The solution for this problem is simple:

double doubleEnglish = Convert.ToDouble(stringEnglish, CultureInfo.InvariantCulture);

This tells C# to accept the notation with the dot. If this is added to both Convert.ToDouble() above, the english string is read correctly (and the german string not).


This is the conversion from string to double. Let's face the other direction. A .ToString() method always returns the notation with the comma on my (german) computer. If I want to save data in C#, e.g. for Gnuplot, this will not work. The solution for this is as simple as the solution above:

string numberEnglish = doubleVariable.ToString(CultureInfo.InvariantCulture);

No comments:

Post a Comment