基本上,我想删除卡路里消耗量的小数位。我知道我需要在self.total2.text = ("\(String(bmi)) kcal")中添加一些内容,但是仅需要一些有关实现此目的的快速建议。

 @IBAction func calc2(_ sender: Any) {
        if self.value111.text! != "" && self.value222.text! != "" {
            let textfieldInt = Float(value111.text!)
            let textfield2Int = Float(value222.text!)
            var bmi:Float = (((textfieldInt! * 2.204623) * 0.5) / 1500) * textfield2Int!
            self.total2.text = ("\(String(bmi)) kcal")
            let banner = StatusBarNotificationBanner(title: "Calculation Done! Submit to save. ✅", style: .warning)
            banner.show(queuePosition: .front)
        }
    }
    @IBAction func submit2(_ sender: Any) {
        let dict = (["kcal": self.total.text!, "date": self.getDate()])
        ref?.child("user").child(Auth.auth().currentUser!.uid).child("measurements").child("calculations").child("kcal").child("\(getDate())").setValue(dict)
        total.text = ""
        let banner = NotificationBanner(title: "Success, Step Calories Burnt has been saved today ⚖️", style: .success)
        banner.show(queuePosition: .front)
    }

最佳答案

使用NumberFormatter(看一下here

let bmi:Float = (((textfieldInt! * 2.204623) * 0.5) / 1500) * textfield2Int!

let formatter = NumberFormatter()

//Set the min and max number of digits to your liking, make them equal if you want an exact number of digits
formatter.minimumFractionDigits = 1
formatter.maximumFractionDigits = 3

self.total2.text = formatter.string(from: NSNumber(value: bmi)) + " kcal"

关于ios - 只显示我的浮点数到某个小数位-Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50180288/

10-14 21:08