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?
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)
}
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
UPDATE more generic definitions
func round<T:BinaryFloatingPoint>(_ value:T, toNearest:T) -> T {
return round(value / toNearest) * toNearest
}
func round<T:BinaryInteger>(_ value:T, toNearest:T) -> T {
return T(round(Double(value), toNearest:Double(toNearest)))
}
and usage
let A = round(-13.16, toNearest: 0.25)
let B = round(8, toNearest: 3.0)
let C = round(8, toNearest: 5)
print(A, type(of: A))
print(B, type(of: B))
print(C, type(of: C))
prints
-13.25 Double
9.0 Double
10 Int
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With