只显示我的浮点数到某个小数位 - Swift

时间:2018-05-04 17:29:43

标签: ios swift

基本上我想删除我的步卡路里燃烧计算的小数位。我知道我需要在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)
    }

2 个答案:

答案 0 :(得分:0)

查看NumberFormatter类,它允许您微调数值的字符串表示形式,无论是整数还是浮点数。设置NumberFormatter以产生所需格式的输出,然后调用string(from:)从您的号码创建一个字符串。

答案 1 :(得分:0)

使用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" (看看here

var candidate = Contituencies
.SelectMany(constituency => constituency.Candidates.Select(candidate => 
   new 
   {
     Constituency = constituency, 
     Candidate = candidate
   }))
.OrderByDescending(candidateInfo => candidateInfo.Candidate.Votes).FirstOrDefault();
string constituencyName = candidate.Constituency.ConstituencyName;
string candidatename = candidate.Candidate.CandidateName;
int votes = candidate.Candidate.Votes;