我是Swift编程的新手,我一直在Xcode 8.2中创建一个简单的tip计算器应用程序,我的计算设置在我的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)"
}
}
Run Code Online (Sandbox Code Playgroud)