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

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

    Extension for Swift 2

    A more general solution is the following extension, which works with Swift 2 & iOS 9:

    extension Double {
        /// Rounds the double to decimal places value
        func roundToPlaces(places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return round(self * divisor) / divisor
        }
    }
    


    Extension for Swift 3

    In Swift 3 round is replaced by rounded:

    extension Double {
        /// Rounds the double to decimal places value
        func rounded(toPlaces places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self * divisor).rounded() / divisor
        }
    }
    


    Example which returns Double rounded to 4 decimal places:

    let x = Double(0.123456789).roundToPlaces(4)  // x becomes 0.1235 under Swift 2
    let x = Double(0.123456789).rounded(toPlaces: 4)  // Swift 3 version
    

提交回复
热议问题