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

I want to round to the nearest half in Double

. For example, if a number 3.76

, I want to round it up to 4

. On the other hand, if a number 3.74

, I want to round up 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

      

+3


source to share


2 answers


Card N → N * 2, round, card N → N / 2.



extension Double{
    func roundToClosestHalf() -> Double {
        return (self*2).rounded() / 2
    }
}

      

+10


source


Update: gender only (thanks to Rob for the warning)

Here's a shorter version:



extension Double{
    func roundToClosestHalf() -> Double{
        return Double(Int(self*2))/2
    }
}

      

0


source







All Articles