Round Double to closest 10
You can use the round()
function (which rounds a floating point numberto 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)) // 0print(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)}
defining the rounding function as
import Foundationfunc 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.25let r1 = round(325, toNearest: 10) // 330.0let r3 = round(.pi, toNearest: 0.0001) // 3.1416
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.0value.rounded(to: 10) // 330 (default rounding mode toNearestOrAwayFromZero)value.rounded(to: 10, roundingRule: .down) // 320