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