Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing numbers from different cultures in C#

Tags:

c#

culture

I'm writing some code to parse a string into a double, but this string is passed to me from another machine. Naturally a problem has occurred where the culture may be different. So, while machine A might send me:

"0.5"

Machine B might send me

"0,6"

Because it's in Germany and has a different culture.

What's the best way to correctly parse both of these inputs? Someone suggested using CultureInfo.InvariantCulture as an argument to Convert.ToDouble but won't that only help where I'm producing the above strings, not when someone else can send me different ones?

Am I right in thinking I'll need to know the source culture and change Thread.CurrentThread.CurrentCulture to match before attempting to convert?

like image 206
Martin Avatar asked Jan 18 '12 11:01

Martin


2 Answers

If you know the source culture, and can get a CultureInfo instance representing it, you can pass this to the Convert.ToDouble or Double.Parse method as a parameter. For instance, if you have this from a (known) German user:

var cultureInfo = CultureInfo.GetCultureInfo("de-DE");
double result = Double.Parse("0,5", cultureInfo);

If you're not sure, but have a limited range of source cultures, then you could use a number of Double.TryParse attempts with the various cultures. However, as has been pointed out below, "1,000" could have quite different meanings depending on the culture...

like image 192
David M Avatar answered Sep 28 '22 07:09

David M


Is it a machine or a person that's sending this? If it's a machine - that is to say, there's an application on another machine that decides what data to send rather than it being a "blind" transmission of user input, then the format for such things should be specified rather than locale-dependent. Generally this means you both agree to use CultureInfo.InvariantCulture or a culture equivalent to that if the other application is not .NET.

If it's a person and you know their locale, then you can use double.Parse(decString, cultureInfo). This can fail if e.g some English-speaking person borrows their German-speaking friend's computer.

If you know there won't be any grouping separators (e.g. 123,456.78 or 123'457,78) then you can use double.Parse(decString.Replace(',', '.'), CultureInfo.InvariantCulture) but can't if there's groupings as that means 123,456.78 becomes 123.456.78.

like image 37
Jon Hanna Avatar answered Sep 28 '22 08:09

Jon Hanna