我正在尝试从类似以下的字符串中提取双精度值:
"0.01 USD"
问题是它无法正常工作,我找不到我的案例的例子。
我在Xcode中的代码
private func extractDoubleFromTextField(textField: UITextField) -> Double {
var result : Double = 0.0
let currentText = textField.text
print("extracted text: \(currentText!)")
if (currentText != nil) {
let scanner = Scanner.localizedScanner(with: currentText!)
(scanner as AnyObject).scanDouble(&result)
}
print("result before return: \(String(format:"%.2f", result))")
return result
}
输出:
extracted text: 0.01
result before return: 0.00
在Playground中执行相同的代码可以为我提供正确的值:
var result : Double = 0.0
let currentText = "0.01"
if (currentText != nil) {
let scanner = Scanner.localizedScanner(with: currentText)
(scanner as AnyObject).scanDouble(&result)
}
print(result)
输出:
0.01
更新
函数scanDouble即使在情况为“ 0.01”-> 0.00时也返回true(成功)
并在虚拟设备上进行测试,可以得出正确的结果: “ 0.01”-> 0.01