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

前端 未结 28 3228
日久生厌
日久生厌 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:54

    Use the built in Foundation Darwin library

    SWIFT 3

    extension Double {
        func round(to places: Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return Darwin.round(self * divisor) / divisor
        }
    }
    

    Usage:

    let number:Double = 12.987654321
    print(number.round(to: 3)) 
    

    Outputs: 12.988

提交回复
热议问题