I’m using XML files to store user data. Files may be saved and loaded from different localisation. Depending on the culture, a double number can be saved as “1.2345” or as “1,2345”. The difference is the decimal separator.
Currently I’m using the following code for parsing:
private double StringToDouble(string input)
{
string decimalPoint = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
if (!input.Contains(decimalPoint))
{
input = input.Replace(".", decimalPoint);
input = input.Replace(",", decimalPoint);
}
return double.Parse(input);
}
The code above works well, but obviously it is not the best.
Can you offer a better solution?
Honestly I don’t think your current solution is too bad. It isn’t elegant, but you are given non-elegant data. As others have suggested, I would see if it is possible to get the XML files in a consistent format, or at least have the XML files saved with a culture info:
That way you won’t have to guess.
Barring that, you could also do something like this:
CultureInfo.Cloneis expensive, but you can cache culture info based on what the separator is. This also gives you the flexibility to set up different thousands separators, if needed. You would have to assume what the thousands separator is depending on the decimal separator.