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

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

    This is more flexible algorithm of rounding to N significant digits

    Swift 3 solution

    extension Double {
    // Rounds the double to 'places' significant digits
      func roundTo(places:Int) -> Double {
        guard self != 0.0 else {
            return 0
        }
        let divisor = pow(10.0, Double(places) - ceil(log10(fabs(self))))
        return (self * divisor).rounded() / divisor
      }
    }
    
    
    // Double(0.123456789).roundTo(places: 2) = 0.12
    // Double(1.23456789).roundTo(places: 2) = 1.2
    // Double(1234.56789).roundTo(places: 2) = 1200
    

提交回复
热议问题