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
Map N -> N*2, round, map N -> N/2.
extension Double{
func roundToClosestHalf() -> Double {
return (self*2).rounded() / 2
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With