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

前端 未结 28 2539
日久生厌
日久生厌 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:54

    If you want to round Double values, you might want to use Swift Decimal so you don't introduce any errors that can crop up when trying to math with these rounded values. If you use Decimal, it can accurately represent decimal values of that rounded floating point value.

    So you can do:

    extension Double {
        /// Convert `Double` to `Decimal`, rounding it to `scale` decimal places.
        ///
        /// - Parameters:
        ///   - scale: How many decimal places to round to. Defaults to `0`.
        ///   - mode:  The preferred rounding mode. Defaults to `.plain`.
        /// - Returns: The rounded `Decimal` value.
    
        func roundedDecimal(to scale: Int = 0, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
            var decimalValue = Decimal(self)
            var result = Decimal()
            NSDecimalRound(&result, &decimalValue, scale, mode)
            return result
        }
    }
    

    Then, you can get the rounded Decimal value like so:

    let foo = 427.3000000002
    let value = foo.roundedDecimal(to: 2) // results in 427.30
    

    And if you want to display it with a specified number of decimal places (as well as localize the string for the user's current locale), you can use a NumberFormatter:

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 2
    formatter.minimumFractionDigits = 2
    
    if let string = formatter.string(for: value) {
        print(string)
    }
    

提交回复
热议问题