ios - 从 String 转换为 Double 导致 Swift 崩溃

标签 ios swift parsing type-conversion nsnumberformatter

我正在尝试转换文本字段的文本,由于十进制数字键盘,它只能是数字。

我正在使用的变量:

static var selectedMoneyMissing: Double = 30.0

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.roundingMode = .down

let roundedReplacing = formatter.string(from: NSNumber(value: Double(textField.text!.replacingOccurrences(of: ",", with: "."))!))

let roundedReplacingSecond = roundedReplacing.replacingOccurrences(of: " ", with: "")
print(roundedReplacing)
print(roundedReplacingSecond)

FiltersViewController.selectedMoneyMissing = Double(roundedReplacingSecond)!

我收到“意外发现 nil...”错误:

screenshot

此错误仅在我输入值 >= 1000 时发生。所以我认为这可能是因为空白,这就是 roundedReplacingSecond 变量存在的原因。但它仍然不起作用(实际上,我不知道为什么控制台打印带有空格的变量“roundedReplacingSecond”?)。

最佳答案

您应该将 NumberFormatter 配置得更严格,尤其是禁止使用分组和千位分隔符:

formatter.groupingSeparator = false
formatter.hasThousandSeparator = false

有关更多属性,请参阅文档。那么根本不需要进行文本替换,这可能会因用户区域设置而中断。

关于ios - 从 String 转换为 Double 导致 Swift 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47562294/

相关文章:

iphone - 将 TTImageView 设置为 TTView 的背景

objective-c - 带有字体名称和粗体的 UITextView 格式

ios - UISegmentedControl 没有触发 UIControlEventValueChanged

ios - Swift - 调用中参数 "coder"缺少参数

ios - 尝试呈现 View 不在层次结构中的 Controller

c - C中的碎片化和取消碎片化文件

ios - 从子级调用父 View 上的 PerformSegueWithIdentifier 不会更改 View

swift - 如何通过按下按钮在 View 中快速添加多个标签?

c - 在 C 语言中解析 DSL 比 lex/yacc 更好的解决方案?

ios - swift ,Alamofire,SwiftyJSON : How to parsing arrayObject