首页 > 解决方案 > 如何将四舍五入的整数显示到标签?

问题描述

我正在尝试制作一个将 UILabel 中的整数四舍五入的函数。我有两个 totalLabel.text 方法,但是在声明了第二个之后,我发现总数现在刚刚四舍五入。我正在尝试使它显示原始的十进制数字,并且当按下按钮时,它会将总数向上舍入。代码:

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func onTap(_ sender: Any) {
        view.endEditing(true)
    }
    

    @IBAction func updateTip(_ sender: Any) {
        updateUI()
     
    }
    
    
    @IBAction func splitTotal(_ sender: UIStepper) {
        updateUI()
    }
    
    @IBAction func roundUpButtonPressed(_ sender: UIButton) {
        updateUI()
    }

    func updateUI() -> Void {
        let tipPercentages = [0.10, 0.15, 0.20, 0.25]
        let numPeople = stepper.value
        let bill = Double(billField.text!) ?? 0
        let tip = bill * tipPercentages[tipController.selectedSegmentIndex]
        let total = bill + tip
        
        let totalSplit = total / numPeople
        let tipSplit = tip / numPeople

        // roundUp declaration.
        let roundUp = round(total)
        
        tipLabel.text = String(format: "$%.2f", tip)
        totalLabel.text = String(format: "$%.2f", total)
        splitTotal.text = String(format: "$%.2f", totalSplit)
        splitTip.text = String(format: "$%.2f", tipSplit)
        
        // Display rounded total to total label.
        totalLabel.text = String(format: "$%.2f", roundUp)
        
        numberOfPeople.text = "\(Int(numPeople))"
        
    }
    
}


标签: iosswiftiphonexcode

解决方案


推荐阅读