在 Swift 中通过 String(format:...) 将 Decimal 转换为 String

Converting Decimal to String by String(format:...) in Swift

你能帮我解决一个案例吗: 当我尝试“eachPersonPays”将 Decimal 转换为 String 时,出现错误“Argument type 'Decimal' does not conform to expected type 'CVarArg'”。 当我确认修复为“as CVarArg”时,我没有计算“totalBill”。

我该怎么做: totalBill = String(格式: "%.2", eachPersonPays) 这样我就可以计算出 totalBill。

@IBAction func calculatePressed(_ sender: UIButton) {
    bill = billTextField.text!
    if (Decimal(string: bill) != nil) == true {
        let eachPersonPays: Decimal = (Decimal(string: bill)! * tip) / Decimal(string: numberOfPeople)!
        totalBill = String(format: "%.2", eachPersonPays)
        print(totalBill)
        self.performSegue(withIdentifier: "goToResult", sender: self)
        
    } else {
        billTextField.text = "input bill amount"

P.S。 我希望我能正确解释我遇到的问题。

缺少数字对象 @ 的说明符:format: "%@.2"

顺便说一句

if (Decimal(string: bill) != nil) == true

太可怕了不灵巧,还有Optional Binding

if let decimalBill = Decimal(string: bill),
   let decimalNumberOfPeople = Decimal(string: numberOfPeople) {
     let eachPersonPays = decimalBill * tip / decimalNumberOfPeople
     let totalBill = String(format: "%@.2", eachPersonPays as CVarArg) // or as NSNumber
}