我试图创建一个从两个UITextField接收输入的应用程序,将它们相乘并在第三个UITextField中返回产品。
import UIKit
class ParallelogramSurfaceArea: UIViewController {
@IBOutlet weak var sideA: UITextField!
@IBOutlet weak var height: UITextField!
@IBOutlet weak var surfaceArea: UITextField!
@IBAction func calculate(sender: AnyObject) {
let aText = (sideA.text! as NSString).doubleValue
let hText = (height.text! as NSString).doubleValue
let a = round(10000 * aText)/10000
let h = round(10000 * hText)/10000
let sa = round(10000*(a * h))/10000
sideA.text = "Side A = \(a) m"
height.text = "Height = \(h) m"
surfaceArea.text = "Surface Area = \(sa) m²"
}
问题是,在十进制小键盘上,','出现而不是'。'因为区域设置导致计算错误。我如何使用NSNumberFormatter解决这个问题?有关改进class ParallelogramSurfaceArea
的建议吗?
答案 0 :(得分:2)
如果要将字符串转换为double并考虑当前本地,NSNumberFormatter
默认情况下将local
值设置为当前区域设置
let numberFormatter = NSNumberFormatter()
numberFormatter.locale = NSLocale.currentLocale() // default value
// or custom local
numberFormatter.locale = NSLocale(localeIdentifier: "fr_FR")
let stringValue = sideA.text as? String ?? ""
let doubleValue = numberFormatter.numberFromString(stringValue)?.doubleValue ?? 0.0