Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round Double to closest 10

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?

like image 875
Tom Coomer Avatar asked Jan 13 '15 12:01

Tom Coomer


3 Answers

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)
}
like image 54
Martin R Avatar answered Oct 11 '22 14:10

Martin R


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
like image 31
user3441734 Avatar answered Oct 11 '22 13:10

user3441734


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
like image 8
Leo Dabus Avatar answered Oct 11 '22 14:10

Leo Dabus