我有这个代码打印出一定数量的钱,但有时如果金额达到10美分的倍数,如22.50美元或189.20美元,用户界面会砍掉最后的0,显示22.5美元或189.2美元?
@IBAction func btnCalPress(sender: AnyObject) {
let tipPer = Double(PercentTip.text!)! / 100
let billAmt = Double(BillAmount.text!)
let salesTax = Double(SalesTax.text!)! / 100
let tipAmt = Double(billAmt! * tipPer)
let taxAmt = Double(billAmt! * salesTax)
let totalAmt = tipAmt + taxAmt + billAmt!
let tipAmountFormat = round(tipAmt * 100) / 100
let taxAmountFormat = round(taxAmt * 100) / 100
let totalPayFormat = round(totalAmt * 100) / 100
TipAmount.text = "Tip: $\(tipAmountFormat)"
TaxAmount.text = "Tax: $\(taxAmountFormat)"
TotalAmount.text = "Total: $\(totalPayFormat)"
}
答案 0 :(得分:3)
在处理货币时,更容易依赖NSNumberFormatter
,这恰好也可以处理某些货币的特定情况。
应用于您的代码:
@IBAction func btnCalPress(sender: AnyObject) {
let tipPer = Double(PercentTip.text!)! / 100
let billAmt = Double(BillAmount.text!)!
let salesTax = Double(SalesTax.text!)! / 100
let tipAmt = Double(billAmt * tipPer)
let taxAmt = Double(billAmt * salesTax)
let totalAmt = tipAmt + taxAmt + billAmt
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
let tipAmount = formatter.stringFromNumber(tipAmt)!
let taxAmount = formatter.stringFromNumber(taxAmt)!
let totalAmount = formatter.stringFromNumber(totalAmt)!
TipAmount.text = "Tip: \(tipAmount)"
TaxAmount.text = "Tax: \(taxAmount)"
TotalAmount.text = "Total: \(totalAmount)"
}
答案 1 :(得分:0)
就像@jtbandes所说,在处理货币时,您应该使用NSDecimalNumber
,而不是Double
或Float
,否则您将失去精确度。
虽然浮点类型可以存储大数字:
print(FLT_MAX) // 3.40282e+38
print(DBL_MAX) // 1.79769313486232e+308
它们不适合货币,因为如果您的金额具有大量小数位,您将失去精确度:
let amountString = "9999999999.000009"
let amountDouble = Double(amountString)!
print(amountDouble)
// prints 9999999999.00001 notice how the .000009 was rounded up to .00001
let amountDecimalNumber = NSDecimalNumber(string: amountString)
print(amountDecimalNumber) // prints 9999999999.000009 no precision lost
在处理货币时,没有理由失去精确度,超过数百万的交易,小的舍入错误确实加起来! 仅限演示文字。
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
let prettyAmount = formatter.stringFromNumber(amountDecimalNumber)
// prints $9,999,999,999.00