Not every place in the world uses the full stop (or period) as a decimal mark. Quite a few use the comma instead.
Simple and perhaps obvious to some, though it's bitten me twice now. I first ran into it three years ago in Fourcast and fixed it there. More recently, the same thing came up again in ForecastPCL - I'd completely forgotten about it. Hopefully writing this will help in remembering the problem in the future .
Both Fourcast and ForecastPCL involve converting latitude and longitude coordinates (with their decimal point) to or from strings. Both rely on a web service which uses these coordinates with a full stop as the decimal. And both failed when the code ran on a device in a locale where the comma is the decimal mark instead.
The reason is simple: in .NET, both
Double.Parse() use the formatting conventions of the device's culture. So you're fine if your code runs on a system set to a locale with full stops as the decimal, but everything explodes elsewhere.
For instance, consider this example (using scriptcs): we set the current thread to use
en-US, a region where the period is the decimal mark.
But if we switch to a region which uses commas instead - say, France:
In a less-contrived example, we can look at (a simplified version of) the problematic code from ForecastPCL:
In this case, the formatting works - it just gives us an incorrect URL, leading to a bad request:
The solution to all of these problems is to use the invariant culture - an English-associated but non-region-specific culture that's useful for formatting issues like this .
String.Format can take in an
IFormatProvider as its first argument, which solves our problem:
Double.Parse takes in
IFormatProvider, though as its last argument:
Pretty simple, though it does mean it gets sprinkled throughout the code. An alternative might be to change the thread to use the invariant culture before doing any parsing, then changing it back to the native one after. This strikes me as being really hackish and more of a workaround than an actual solution, though.