roc*_*101 47 rounding swift xcode6
在玩游戏时,我在swift中找到了round()函数.它可以用如下:
round(0.8)
Run Code Online (Sandbox Code Playgroud)
哪个将按预期返回1.这是我的问题:
我怎么快速地绕千分之一?
我希望能够插入一个数字,比如0.6849,然后回到0.685.round()如何做到这一点?或者,它不是,在这种情况下,什么功能呢?
Clé*_*lon 81
你可以做:
round(1000 * x) / 1000
Run Code Online (Sandbox Code Playgroud)
Sur*_*gch 15
这round(someDecimal)
是旧的C风格.从Swift 3开始,双精度和浮点数具有内置的Swift功能.
var x = 0.8
x.round() // x is 1.0 (rounds x in place)
Run Code Online (Sandbox Code Playgroud)
要么
var x = 0.8
var y = x.rounded() // y is 1.0, x is 0.8
Run Code Online (Sandbox Code Playgroud)
有关如何使用不同的舍入规则的更多详细信息,请在此处(或此处)查看我的答案更全面的答案.
正如其他答案所指出的那样,如果你想要舍入到千分之一,那么1000
在你回合前暂时加倍.
小智 10
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)
Run Code Online (Sandbox Code Playgroud)
这是一种方法.你可以很容易地做到这一点Float
,或者可能使它成为通用的,所以它适用于任何这些.
public extension CGFloat {
func roundToDecimals(decimals: Int = 2) -> CGFloat {
let multiplier = CGFloat(10^decimals)
return round(multiplier * self) / multiplier
}
}
Run Code Online (Sandbox Code Playgroud)