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?
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...
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With