c# - Double.TryParse() 忽略 NumberFormatInfo.NumberGroupSizes?

标签 c# .net parsing double

我想知道我是否遗漏了什么......我在标准的大不列颠文化下运行。

Double result = 0;
if (Double.TryParse("1,2,3", NumberStyles.Any, CultureInfo.CurrentCulture, out result))
{
   Console.WriteLine(result);
}

预期的输出是什么...“1,2,3”不应解析为 double 。然而它确实如此。根据 .NET 2.0 MSDN documentation

AllowThousands Indicates that the numeric string can have group separators; for example, separating the hundreds from the thousands. Valid group separator characters are determined by the NumberGroupSeparator and CurrencyGroupSeparator properties of NumberFormatInfo and the number of digits in each group is determined by the NumberGroupSizes and CurrencyGroupSizes properties of NumberFormatInfo.

Allow thousands 包含在 NumberStyles.Any 中。 NumberGroupSizes 对于我的文化是 3。这只是 Double.Parse 中的一个错误吗?似乎不太可能,但我无法发现我做错了什么....

最佳答案

这只是意味着输入字符串可以包含零个或多个 NumberFormatInfo.NumberGroupSeparator 实例。此分隔符可用于分隔任意大小的数字组;不只是成千上万。 NumberFormatInfo.NumberGroupSeparatorNumberFormatInfo.NumberGroupSizes 用于将小数格式化为字符串。使用 Reflector 似乎 NumberGroupSeparator 仅用于确定字符是否为分隔符,如果是,则跳过。 NumberGroupSizes 根本没有使用。

如果要验证字符串,可以使用 RegEx 或编写一个方法来验证字符串。这是我刚刚一起破解的:

string number = "102,000,000.80";
var parts = number.Split(',');
for (int i = 0; i < parts.Length; i++)
{
    var len = parts[i].Length;
    if ((len != 3) && (i == parts.Length - 1) && (parts[i].IndexOf('.') != 3))
    {
        Console.WriteLine("error");
    }
    else
    {
        Console.WriteLine(parts[i]);
    }
}

// Respecting Culture
static Boolean CheckThousands(String value)
{
    String[] parts = value.Split(new string[] { CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator }, StringSplitOptions.None);
    foreach (String part in parts)
    {
        int length = part.Length;
        if (CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes.Contains(length) == false)
        {
            return false;
        }
    }

    return true;
}

关于c# - Double.TryParse() 忽略 NumberFormatInfo.NumberGroupSizes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883801/

相关文章:

c# - TableLayoutPanel 从上到下而不是从左到右填充?

c# - unity中Kinect未检测到玩家时触发什么事件

c# - 返回按重复/重复项目计数排序的唯一列表

c# - .NET:静态方法的推断泛型类型

c# - 哪些解析器可用于解析 C# 代码?

c# - 为什么检测到正在更改的对象属性但未检测到刷新对象

java - 需要 HTML 页面作为从一个应用程序到另一应用程序的响应

c# - asp.net 多个文件上传控件的多个上传

C# 如何通过分组解析文本文件?

java - 在java中解析日期和时间