I would like to round a Double
to the closest multiple of 10.
For example if the number is 8.0 then round to 10. If the number is 2.0 round it to 0.
How can I do that?
See Question&Answers more detail:osI would like to round a Double
to the closest multiple of 10.
For example if the number is 8.0 then round to 10. If the number is 2.0 round it to 0.
How can I do that?
See Question&Answers more detail:osYou 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)
}