Swift – How to Round Double to 0.5

roundingswift

i have a result "1.444444" and i want to round this result to "1.5" this is the code i use :

a.text = String(round(13000 / 9000.0))

but this is round to "1.0" and i need round to "1.5"

and this code :

a.text = String(ceil(13000 / 9000.0))

is round to "2.0"

Best Answer

Swift 3:

extension Double {
    func round(nearest: Double) -> Double {
        let n = 1/nearest
        let numberToRound = self * n
        return numberToRound.rounded() / n
    }

    func floor(nearest: Double) -> Double {
        let intDiv = Double(Int(self / nearest))
        return intDiv * nearest
    }
}

let num: Double = 4.7
num.round(nearest: 0.5)      // Returns 4.5

let num2: Double = 1.85
num2.floor(nearest: 0.5)     // Returns 1.5

Swift 2:

extension Double {
    func roundNearest(nearest: Double) -> Double {
        let n = 1/nearest
        return round(self * n) / n
    }
}

let num: Double = 4.7
num.roundNearest(0.5)      // Returns 4.5
Related Question