Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rounding

swift

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
like image 417
fja Avatar asked Dec 19 '22 07:12

fja


1 Answers

Map N -> N*2, round, map N -> N/2.

extension Double{
    func roundToClosestHalf() -> Double {
        return (self*2).rounded() / 2
    }
}
like image 90
Rob Napier Avatar answered Apr 15 '23 17:04

Rob Napier