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

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

    A handy way can be the use of extension of type Double

    extension Double {
        var roundTo2f: Double {return Double(round(100 *self)/100)  }
        var roundTo3f: Double {return Double(round(1000*self)/1000) }
    }
    

    Usage:

    let regularPie:  Double = 3.14159
    var smallerPie:  Double = regularPie.roundTo3f  // results 3.142
    var smallestPie: Double = regularPie.roundTo2f  // results 3.14
    

提交回复
热议问题