Reputation: 6527
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?
Upvotes: 21
Views: 16722
Reputation: 17534
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
Upvotes: 30
Reputation: 46
extension Double {
var roundToTens: Double {
let divideByTen = self / 10
let multiByTen = (ceil(divideByTen) * 10)
return multiByTen
}
}
usage: 36. roundToTens
Upvotes: 0
Reputation: 236360
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
Upvotes: 9
Reputation: 533
Extension for rounding to any number !
extension Int{
func rounding(nearest:Float) -> Int{
return Int(nearest * round(Float(self)/nearest))
}
}
Upvotes: 1
Reputation: 9196
Nice extension for BinaryFloatingPoint in swift:
extension BinaryFloatingPoint{
func roundToTens() -> Int{
return 10 * Int(Darwin.round(self / 10.0))
}
func roundToHundreds() -> Int{
return 100 * Int(Darwin.round(self / 100.0))
}
}
Upvotes: 0
Reputation: 539745
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)
}
Upvotes: 49