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

前端 未结 28 2583
日久生厌
日久生厌 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))
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 06:54

    Use the built in Foundation Darwin library

    SWIFT 3

    extension Double {
        func round(to places: Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return Darwin.round(self * divisor) / divisor
        }
    }
    

    Usage:

    let number:Double = 12.987654321
    print(number.round(to: 3)) 
    

    Outputs: 12.988

    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2020-11-22 06:55

    Swift 4, Xcode 10

    yourLabel.text =  String(format:"%.2f", yourDecimalValue)
    
    0 讨论(0)
提交回复
热议问题