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

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

    You can use Swift's round function to accomplish this.

    To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:

    let x = 1.23556789
    let y = Double(round(1000*x)/1000)
    print(y)  // 1.236
    

    Other than any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double.

    EDIT:
    Regarding the comments that it sometimes does not work, please read this:

    What Every Programmer Should Know About Floating-Point Arithmetic

提交回复
热议问题