2

我在解析/验证文化敏感的数字格式时遇到了 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
4

3 回答 3

0

您应该指定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
于 2013-07-23T13:59:20.527 回答
0

您可以在此处找到有关解析的信息,如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

于 2013-07-23T13:53:53.207 回答
0

为了正确解析数字,您肯定需要数字的源文化信息。请参阅此 Parsing numbers from differentcultures in C#

于 2013-07-24T06:43:32.233 回答