我在解析/验证区域性敏感数字格式时遇到了C#(和Java)的问题。当涉及到数字分组时,分隔符可以放在.NET中的任何位置。有没有办法严格遵守数字分组的用法?例如,请参见以下内容:
Decimal.Parse("9,0"); /// Returns 90, which is wrong
Decimal.Parse("90,00"); /// Returns 9000, which is wrong
Decimal.Parse("9,000"); /// Returns 9000, which is right
更复杂的是,不同文化在每组数字的数量上有所不同。
有什么建议吗?
编辑:有人建议我将CultureInfo添加到Parse()中,但这仍然不能正常工作。例如:
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); /// Murican English
Double.Parse("9,0", culture); /// Returns 90 when it should throw an exception
culture = CultureInfo.CreateSpecificCulture("pt-BR"); /// Brazillian Portuguese
Double.Parse("9.0", culture); /// Returns 90 when it should throw an exception
您可以在这里找到有关解析的信息,如链接中的示例所示,使用CultureInfo culture
例如
culture = CultureInfo.CreateSpecificCulture("en-US");
number = Double.Parse(value, culture);// 1,304.16 --> 1304.16
但是"en-US"无法解析"1 304,16"。"fr-fr"可以-->您将获得1304.16
您应该指定CultureInfo,因为解析结果依赖于区域性。例如
// English, United States:
// "," is a thousand but not decimal separator, decimal separator is "."
// d1 = 90 since "," is NOT a decimal separator
Decimal d1 = Decimal.Parse("9,0", new CultureInfo("en-US")); // <- 90
// Russian, Russia:
// "," is a decimal separator
// d2 = 9.0 since "," is a decimal separator
Decimal d2 = Decimal.Parse("9,0", new CultureInfo("ru-RU")); // <- 9.0
为了正确解析数字,您需要数字的源区域性信息。请参阅在C#中分析不同文化的数字