Rounding a double value to x number of decimal places in swift

前端 未结 28 2602
日久生厌
日久生厌 2020-11-22 06:11

Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

var totalWorkTimeInHours = (totalWorkTime/60/60)
         


        
28条回答
  •  旧时难觅i
    2020-11-22 06:37

    This is a fully worked code

    Swift 3.0/4.0/5.0 , Xcode 9.0 GM/9.2 and above

    let doubleValue : Double = 123.32565254455
    self.lblValue.text = String(format:"%.f", doubleValue)
    print(self.lblValue.text)
    

    output - 123

    let doubleValue : Double = 123.32565254455
    self.lblValue_1.text = String(format:"%.1f", doubleValue)
    print(self.lblValue_1.text)
    

    output - 123.3

    let doubleValue : Double = 123.32565254455
    self.lblValue_2.text = String(format:"%.2f", doubleValue)
    print(self.lblValue_2.text)
    

    output - 123.33

    let doubleValue : Double = 123.32565254455
    self.lblValue_3.text = String(format:"%.3f", doubleValue)
    print(self.lblValue_3.text)
    

    output - 123.326

提交回复
热议问题