问题描述
为了解析一个代表数字的字符串,并用逗号分隔其余的千位数字,我尝试了
To parse a string representing a number, with a comma separating thousand digits from the rest, I tried
int tmp1 = int.Parse("1,234", NumberStyles.AllowThousands);
double tmp2 = double.Parse("1,000.01", NumberStyles.AllowThousands);
第一个语句执行没有问题,而第二个语句失败,但有一个例外:
The first statement is executed without issues, while the second fails with an exception:
其他信息:输入字符串的格式不正确.
Additional information: Input string was not in a correct format.
为什么都不能成功?
推荐答案
您应通过 AllowDecimalPoint
, Float
,或 Number
样式(后两种样式只是几种数字样式的组合,其中包括 AllowDecimalPoint
标志):
You should pass AllowDecimalPoint
, Float
, or Number
style (latter two styles are just a combination of several number styles which include AllowDecimalPoint
flag):
double.Parse("1,000.01", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint)
当您为解析方法提供某种数字样式时,您可以指定可以在字符串中显示的元素的 exact 样式.未包含的样式被认为是不允许的.用于解析双精度值的标志的默认组合(当您未明确指定样式时)是 NumberStyles.Float
和 NumberStyles.AllowThousands
标志.
When you provide some number style to parsing method, you specify exact style of elements which can present in the string. Styles which are not included considered as not allowed. Default combination of flags (when you don't specify style explicitly) for parsing double value is NumberStyles.Float
and NumberStyles.AllowThousands
flags.
考虑解析整数的第一个示例-您尚未传递 AllowLeadingSign
标志.因此,以下代码将引发异常:
Consider your first example with parsing integer - you haven't passed AllowLeadingSign
flag. Thus the following code will throw an exception:
int.Parse("-1,234", NumberStyles.AllowThousands)
对于此类数字,应添加 AllowLeadingSign
标志:
For such numbers, AllowLeadingSign
flag should be added:
int.Parse("-1,234", NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign)
这篇关于在此示例中,为什么NumberStyles.AllowThousands可用于int.Parse但不能用于double.Parse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!