[英]What is the best way to parse double from unknown culture in .NET C#?
I'm using XML files to store user data. 我正在使用XML文件来存储用户数据。 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". 根据文化,双号可以保存为“1.2345”或“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? 你能提供更好的解决方案吗?
If you serialize your double to your xml file as a double primitive and not as a string, it will save it with "." 如果将double作为double原语而不是字符串序列化为xml文件,它将使用“。”将其保存。 so you can parse it with invariant culture. 所以你可以用不变的文化来解析它。
If it's saved as text, you can try something like this: 如果它保存为文本,您可以尝试这样的事情:
double result = double.Parse(input.Replace(",", "."), CultureInfo.InvariantCulture);
Note that you can still have problems with thousands separators in numbers like "1.234.567,89". 请注意,您仍然可能遇到数千个分隔符的问题,例如“1.234.567,89”。
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: 正如其他人所建议的那样,我会看到是否可以以一致的格式获取XML文件,或者至少使用文化信息保存XML文件:
<yourRootElement xml:lang="en-US">
That way you won't have to guess. 那样你就不用猜了。
Barring that, you could also do something like this: 除此之外,您还可以这样做:
private double StringToDouble(string input)
{
var last = input.LastIndexOfAny(new[] {',', '.'});
var separator = last >= 0 ? input[last] : '.';
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.NumberDecimalSeparator = separator.ToString(CultureInfo.InvariantCulture);
return double.Parse(input, clone);
}
CultureInfo.Clone
is expensive, but you can cache culture info based on what the separator is. CultureInfo.Clone
很昂贵,但您可以根据分隔符的内容缓存文化信息。 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. 你必须假设千位分隔符取决于小数分隔符。
I would recommend to save numbers in a fixed fformat, ie with fixed decimal separator. 我建议将数字保存在固定的格式中,即使用固定的小数分隔符。 This means that transformation from the user's culture to the culture in which number must be saved should be performed. 这意味着应该执行从用户文化到必须保存数字的文化的转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.