为什么不能'TryParse解析数字分组(但double).TryParse可以)

本文关键字:TryParse double 可以 不能 为什么 数字 | 更新日期: 2023-09-27 17:49:45

在c#中,为什么不能int。TryParse解析数字分组(但double)。TryParse)吗?

        int i1 = 13579;
        string si1 = i1.ToString("N0");  //becomes 13,579
        int i2 = 0;
        bool result1 = int.TryParse(si1, out i2); //gets false and 0
        double d1 = 24680.0;
        string sd1 = d1.ToString("N0"); //becomes 24,680
        double d2 = 0;
        bool result2 = double.TryParse(sd1, out d2); //gets true and 24680.0

? ?

为什么不能'TryParse解析数字分组(但double).TryParse可以)

您必须指定允许的NumberStyles,在将字符串解析回数字时将其考虑在内。

决定传递给整型和浮点型数值类型的Parse和TryParse方法的数值字符串参数所允许的样式。

返回true并将期望的数字存储在i2中:

bool result1 = int.TryParse(si1,
   NumberStyles.AllowThousands, CultureInfo.CurrentCulture.NumberFormat, out i2);

您可能还想看看其他NumberStyles选项。例如,NumberStyles.Number允许千位、小数点、空白等。


int.TryParse的默认值(如果没有指定)是NumberStyles.Integer,它只允许一个前导符号,以及前后空白。

double.TryParse的默认值是NumberStyles.Float| NumberStyles.AllowThousands,它允许前导符号和空格,但也允许千位、指数和小数点。

因为两种数据类型的转换因子不同。在字符串值中分配的参数将不同于这两种数据类型。

Int。TryParse不包含转换参数

形式的区域性千位分隔符参数例如

Int。解析参数的形式为

[ws][sign]digits[ws]
ws: White space (optional)
sign: An optional Sign (+-)
digit: sequance of digit (0-9)

和十进制。解析参数的形式为

[ws][sign][digits,]digits[.fractional-digits][ws]
ws: White space (optional)
sign: An optional Sign (+-)
digit: sequance of digit (0-9)
,: culture specific thousand separator
.: culture specific decimal point.
fractional-digits: fractional digit after decimal point.

您可以从msdn获得更多信息。Int。TryParse和Decimal。TryParse