Rounding in Swift with round()

前端 未结 7 445
星月不相逢
星月不相逢 2020-12-08 01:52

While playing around, I found the round() function in swift. It can be used as below:

round(0.8)

Which will return 1, as expected. Here\'s

相关标签:
7条回答
  • 2020-12-08 02:27

    This will round to any value not limited by powers of 10.

    extension Double {
        func roundToNearestValue(value: Double) -> Double {
            let remainder = self % value
            let shouldRoundUp = remainder >= value/2 ? true : false
            let multiple = floor(self / value)
            let returnValue = !shouldRoundUp ? value * multiple : value * multiple + value
            return returnValue
        }
    }
    
    0 讨论(0)
  • 2020-12-08 02:29
    func round(value: Float, decimalPlaces: UInt) {
      decimalValue = pow(10, decimalPlaces)
      round(value * decimalValue) / decimalValue
    }
    …
    func round(value: CGFloat, decimalPlaces: UInt)
    func round(value: Double, decimalPlaces: UInt)
    func roundf(value: Float, decimalPlaces: UInt)
    
    0 讨论(0)
  • 2020-12-08 02:33

    You can do:

    round(1000 * x) / 1000
    
    0 讨论(0)
  • 2020-12-08 02:35

    Updated answer

    The round(someDecimal) is the old C style. As of Swift 3, doubles and floats have a built in Swift function.

    var x = 0.8
    x.round() // x is 1.0 (rounds x in place)
    

    or

    var x = 0.8
    var y = x.rounded() // y is 1.0, x is 0.8
    

    See my answer fuller answer here (or here) for more details about how different rounding rules can be used.

    As other answers have noted, if you want to round to the thousandth, then multiply temporarily by 1000 before you round.

    0 讨论(0)
  • 2020-12-08 02:44

    Take a look at Apple's documentation for round() and rounded(_:).

    0 讨论(0)
  • 2020-12-08 02:46

    Swift 4:

    (x/1000).rounded()*1000
    
    0 讨论(0)
提交回复
热议问题