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?
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.InvariantCultureor 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 means123,456.78becomes123.456.78.