我是Swift编程的新手,我一直在Xcode 8.2中创建一个简单的小费计算器应用程序,在IBAction下面的代码中进行了设置。但是,当我实际运行我的应用并输入要计算的金额(例如23.45)时,它会显示超过2个小数位。.currency在这种情况下,如何将其格式化为?
IBAction
.currency
@IBAction func calculateButtonTapped(_ sender: Any) { var tipPercentage: Double { if tipAmountSegmentedControl.selectedSegmentIndex == 0 { return 0.05 } else if tipAmountSegmentedControl.selectedSegmentIndex == 1 { return 0.10 } else { return 0.2 } } let billAmount: Double? = Double(userInputTextField.text!) if let billAmount = billAmount { let tipAmount = billAmount * tipPercentage let totalBillAmount = billAmount + tipAmount tipAmountLabel.text = "Tip Amount: $\(tipAmount)" totalBillAmountLabel.text = "Total Bill Amount: $\(totalBillAmount)" } }
如果要将货币强制为$,可以使用此字符串初始化程序:
String(format: "Tip Amount: $%.02f", tipAmount)
如果希望它完全取决于设备的语言环境设置,则应使用NumberFormatter。这将考虑到货币的小数位数以及正确放置货币符号。例如,双精度值2.4将为es_ES语言环境返回“ 2,40€”,为jp_JP语言环境返回“¥2”。
NumberFormatter
let formatter = NumberFormatter() formatter.locale = Locale.current // Change this to another locale if you want to force a specific locale, otherwise this is redundant as the current locale is the default already formatter.numberStyle = .currency if let formattedTipAmount = formatter.string(from: tipAmount as NSNumber) { tipAmountLabel.text = "Tip Amount: \(formattedTipAmount)" }