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

前端 未结 28 2549
日久生厌
日久生厌 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条回答
  •  长情又很酷
    2020-11-22 06:36

    You can add this extension :

    extension Double {
        var clean: String {
            return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)
        }
    }
    

    and call it like this :

    let ex: Double = 10.123546789
    print(ex.clean) // 10.12
    

提交回复
热议问题