我是 Swift 编程新手,我一直在 Xcode 8.2 中创建一个简单的小费计算器应用程序,我在我的 Xcode 中设置了计算IBAction
以下。但当我实际运行我的应用程序并输入要计算的金额(例如 23.45)时,它会显示超过 2 位小数。我如何将其格式化为.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
。这将考虑货币的小数位数以及正确定位货币符号。例如。对于 es_ES 语言环境,双精度值 2.4 将返回“2,40 €”;对于 jp_JP 语言环境,双精度值 2.4 将返回“¥ 2”。
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)"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)