- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
为了解析表示数字的字符串,用逗号将千位数字与其余数字分开,我试过
int tmp1 = int.Parse("1,234", NumberStyles.AllowThousands);
double tmp2 = double.Parse("1,000.01", NumberStyles.AllowThousands);
第一个语句执行没有问题,而第二个语句失败并出现异常:
An unhandled exception of type 'System.FormatException' occurred inmscorlib.dll
Additional information: Input string was not in a correct format.
为什么不都成功?
最佳答案
你应该通过 AllowDecimalPoint
, Float
, 或 Number
样式(后两种样式只是几种数字样式的组合,其中包括 AllowDecimalPoint
标志):
double.Parse("1,000.01", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint)
当您为解析方法提供一些数字样式时,您指定了可以出现在字符串中的元素的精确样式。未包含的样式视为不允许。用于解析 double 值的默认标志组合(当您未明确指定样式时)是 NumberStyles.Float
和 NumberStyles.AllowThousands
标志。
考虑你的第一个解析整数的例子 - 你没有传递 AllowLeadingSign
标志。因此下面的代码会抛出一个异常:
int.Parse("-1,234", NumberStyles.AllowThousands)
对于这样的数字,应该添加AllowLeadingSign
标志:
int.Parse("-1,234", NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign)
关于c# - 为什么 NumberStyles.AllowThousands 对 int.Parse 有效,但对 double.Parse 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240566/
我有一个具有整数属性的模型。当使用 23443 提交模型时,模型绑定(bind)器运行良好并且该值在操作中可用。但是,如果提交的模型带有千位分隔符,如 23,443,则不会解析该值且该属性为零。但我发
我有一个 NSTextField,我已使用以下代码设置: func tableView(tableView: NSTableView, viewForTableColumn tableColumn:
我正在调用以下两行。第二行崩溃。: var a = long.Parse("2,147,483,648", NumberStyles.AllowThousands); var b = long.Par
我正在尝试解析值为“-51.739253997802734”的经度。 var unknownGeoCoordinate = GeoCoordinate.Unknown; double latitude
为了解析表示数字的字符串,用逗号将千位数字与其余数字分开,我试过 int tmp1 = int.Parse("1,234", NumberStyles.AllowThousands); double
我是一名优秀的程序员,十分优秀!