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

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

    To avoid Float imperfections use Decimal

    extension Float {
        func rounded(rule: NSDecimalNumber.RoundingMode, scale: Int) -> Float {
            var result: Decimal = 0
            var decimalSelf = NSNumber(value: self).decimalValue
            NSDecimalRound(&result, &decimalSelf, scale, rule)
            return (result as NSNumber).floatValue
        }
    }
    

    ex.
    1075.58 rounds to 1075.57 when using Float with scale: 2 and .down
    1075.58 rounds to 1075.58 when using Decimal with scale: 2 and .down

提交回复
热议问题