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

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

    This seems to work in Swift 5.

    Quite surprised there isn't a standard function for this already.

    //Truncation of Double to n-decimal places with rounding

    extension Double {
    
        func truncate(to places: Int) -> Double {
        return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))
        }
    
    }
    

提交回复
热议问题