Rounding in Swift with round()

前端 未结 7 446
星月不相逢
星月不相逢 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:48

    Here's one way to do it. You could easily do this for Float, or probably make it generic so it's for any of those.

    public extension CGFloat {
        func roundToDecimals(decimals: Int = 2) -> CGFloat {
            let multiplier = CGFloat(10^decimals)
            return round(multiplier * self) / multiplier
        }
    }
    
    0 讨论(0)
提交回复
热议问题