Round Double to closest 10
Solution 1:
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)
}
Solution 2:
defining the rounding function as
import Foundation
func round(_ value: Double, toNearest: Double) -> Double {
return round(value / toNearest) * toNearest
}
gives you more general and flexible way how to do it
let r0 = round(1.27, toNearest: 0.25) // 1.25
let r1 = round(325, toNearest: 10) // 330.0
let r3 = round(.pi, toNearest: 0.0001) // 3.1416
Solution 3:
You can also extend FloatingPoint
protocol and add an option to choose the rounding rule:
extension FloatingPoint {
func rounded(to value: Self, roundingRule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Self {
(self / value).rounded(roundingRule) * value
}
}
let value = 325.0
value.rounded(to: 10) // 330 (default rounding mode toNearestOrAwayFromZero)
value.rounded(to: 10, roundingRule: .down) // 320
Solution 4:
In Swift 3.0 it is
10 * Int(round(Double(ratio / 10)))
Solution 5:
Extension for rounding to any number !
extension Int{
func rounding(nearest:Float) -> Int{
return Int(nearest * round(Float(self)/nearest))
}
}