我正在尝试对文本字段进行一些计算,我使用双打来实现它:
let firstValue = Double(miles.text!)
let secondValue = Double(payPerMile.text!)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.locale = Locale.current
formatter.usesGroupingSeparator = true
let result = Double(firstValue! * secondValue!) as NSNumber
grossPay.text = "\(formatter.string(from: result)!)"
在对该主题进行更多研究时,我被告知使用双打并不是最佳选择,所以我尝试使用NSDecimalNumber。
我的问题是我无法弄清楚如何在切换时让它工作。
@IBAction func miles(_ sender: Any) {
let firstValue = NSDecimalNumber(string: miles.text)
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.usesGroupingSeparator = true
miles.text = "\(formatter.string(from: firstValue as NSNumber)!)"
}
@IBAction func payPerMile(_ sender: Any) {
let firstValue = NSDecimalNumber(string: payPerMile.text)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.locale = Locale.current
formatter.usesGroupingSeparator = true
payPerMile.text = "\(formatter.string(from: firstValue as NSNumber)!)"
}
@IBAction func grossPay(_ sender: Any) {
let firstValue = NSDecimalNumber(string: miles.text!)
let secondValue = NSDecimalNumber(string: payPerMile.text!)
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.locale = Locale.current
formatter.usesGroupingSeparator = true
let result = (firstValue as Decimal) * (secondValue as Decimal) as NSDecimalNumber
grossPay.text = "\(formatter.string(from: result)!)"
只是给我NaN的结果
miles.text格式化为.decimal payPerMile.text格式化为.currency
我不确定这是不是我问题的一部分。
答案 0 :(得分:0)
如果payPerMile
的格式为.currency,那么它可能包含货币字符。您不能简单地从这样的字符串创建NSDecimalNumber
。
您的第二行为NaN
提供secondValue
。
您可以使用NumberFormatter
从字符串中获取NSNumber
。
let formatter = NumberFormatter()
formatter.numberStyle = .currency
let payPerMileNumber = formatter.number(from: "$34.75") // NSNumber with 34.75