Is this a good implementation for rounding a Double to the nearest half?

Viewed 332

I want to round to the closest half in a Double. For instance, if the number is 3.76 I want it to be rounded to 4. On the other hand, if the number is 3.74 I want it to round to 3.5.

I came up with this code:

extension Double {
    func roundToClosestHalf() -> Double {
        let upperLimit = ceil(self)
        let difference = upperLimit - self
        if difference <= 0.25 {
            return ceil(self)
        } else if difference > 0.25 && difference < 0.75 {
            return upperLimit - 0.5
        } else {
            return floor(self)
        }
    }
}

Is there a more efficient / better way to do this?

let x = 3.21.roundToClosestHalf() // 3
2 Answers
Related