在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
???
答案 0 :(得分:5)
您必须指定允许的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
,它允许前导符号和空格,但也包含数千,指数和小数点。
答案 1 :(得分:3)
因为两种数据类型的转换因子不同。字符串值中指定的参数将不同于两种数据类型。
Int.TryParse中的不包含转换参数形式的特定于文化的千位分隔符参数
例如
Int.TryParse中的参数形式为
[ws][sign]digits[ws]
ws: White space (optional)
sign: An optional Sign (+-)
digit: sequance of digit (0-9)
并且在Decimal.TryParse中,参数的形式是
[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