Rounding in Swift with round()

2019-01-16 18:09发布

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 my question:

how do I round by thousandths in swift?

I want to be able to plug in a number, say 0.6849, and get 0.685 back. How does round() do this? Or, does it not, in which case, what function does?

6条回答
Viruses.
2楼-- · 2019-01-16 18:24

You can do:

round(1000 * x) / 1000
查看更多
等我变得足够好
3楼-- · 2019-01-16 18:28

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
    }
}
查看更多
可以哭但决不认输i
4楼-- · 2019-01-16 18:32

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
    }
}
查看更多
对你真心纯属浪费
5楼-- · 2019-01-16 18:34

Swift 3

The round(someDecimal) is the old C style. Doubles and floats have a built in Swift function now.

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.

查看更多
迷人小祖宗
6楼-- · 2019-01-16 18:36

Swift 4:

(x/1000).rounded()*1000
查看更多
走好不送
7楼-- · 2019-01-16 18:37
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)
查看更多
登录 后发表回答