You can use the round()
function (which rounds a floating point number
to the nearest integral value) and apply a "scale factor" of 10:
func roundToTens(x : Double) -> Int {
return 10 * Int(round(x / 10.0))
}
Example usage:
print(roundToTens(4.9)) // 0
print(roundToTens(15.1)) // 20
In the second example, 15.1
is divided by ten (1.51
), rounded (2.0
),
converted to an integer (2
) and multiplied by 10 again (20
).
Swift 3:
func roundToTens(_ x : Double) -> Int {
return 10 * Int((x / 10.0).rounded())
}
Alternatively:
func roundToTens(_ x : Double) -> Int {
return 10 * lrint(x / 10.0)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…