我刚接触Swift编程,正在Xcode 8.2中创建一个简单的小费计算器应用程序,我的计算设置在下面的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)"
}
}
locale
设置为Locale.current
,因为这是默认设置。 - rmaddy