首页 > 解决方案 > 在 Swift 中通过 String(format:...) 将十进制转换为字符串

问题描述

你能帮我解决以下情况吗:当我尝试“eachPersonPays”从十进制转换为字符串时,我收到错误“参数类型'十进制'不符合预期的类型'CVarArg'”。当我确认修复为“as CVarArg”时,我没有计算出“totalBill”。

我应该怎么做:totalBill = String(format: "%.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"

PS我希望我能正确解释我遇到的问题。

标签: swiftdecimal

解决方案


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

顺便一提

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

非常不迅速,有可选绑定

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
}

推荐阅读