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

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

    In Swift 3.0 and Xcode 8.0:

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

    Use this extension like so:

    let doubleValue = 3.567
    let roundedValue = doubleValue.roundTo(places: 2)
    print(roundedValue) // prints 3.56
    

提交回复
热议问题