简体   繁体   English

C#数字格式处理数字分组

[英]C# Number format dealing with digit grouping

I encountered an issue with C# (and Java) on the parsing/validation of culture-sensitive numerical formatting. 我在解析/验证对文化敏感的数字格式时遇到了C#(和Java)问题。 It seems like when it comes to digit grouping, the separator can be placed anywhere in .NET. 似乎在进行数字分组时,分隔符可以放在.NET中的任何位置。 Is there a way to enforce a strict adherence of the usage of the digit grouping? 有没有一种方法可以严格遵守数字分组的用法? For instance, see the following: 例如,请参见以下内容:

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

To complicate things, cultures differ in the number of digits per group. 为了使事情复杂化,文化在每组中的位数不同。

Any suggestions? 有什么建议么?

Edit: It was suggested I add CultureInfo into the Parse(), but that does not work properly still. 编辑:建议我将CultureInfo添加到Parse()中,但仍不能正常工作。 For instance: 例如:

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

you can find information on parsing in here as use CultureInfo culture as seen in the example in the link 您可以在此处找到有关解析的信息,如使用CultureInfo culture一样(如链接中的示例所示)

for example 例如

culture = CultureInfo.CreateSpecificCulture("en-US");
number = Double.Parse(value, culture);// 1,304.16 --> 1304.16 

but "en-US" can't parse "1 304,16". 但是“ en-US”无法解析“ 1 304,16”。 "fr-FR" can --> you'll get 1304.16 “ fr-FR”可以->您将获得1304.16

You should specify CultureInfo , since parsing results are culture dependent eg 您应该指定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

For correctly parsing the numbers you definetly need the Source Culture Info of the number. 为了正确解析数字,您明确需要数字的源文化信息。 Refer this Parsing numbers from different cultures in C# 引用来自C#中不同文化的解析数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM