Rounding FloatingPoint type to Nearest Half

I’m writing some code that needs to round a Double up to the nearest multiple of 0.5. I’ve written this extension on FloatingPoint to do so:

extension FloatingPoint {
    
    func rounded(_ rule: FloatingPointRoundingRule, toNearest nearest: Self) -> Self {
        precondition(nearest > 0)
        precondition(nearest < 1)
        
        return (self / nearest).rounded(rule) * nearest
    }
    
}

I’m looking for a better name for nearest inside this method. What would you call it?

I would name this operation

func rounded(_ rule: FloatingPointRoundingRule = .toNearestOrEven, toMultipleOf: Self) -> Self

Calling the argument toNearest is misleading because when a non-default rounding rule is used, the result will not in general be the "nearest" value. It's also important to note that this implementation is only guaranteed to produce a correct result when nearest is a power of two (and even then it can overflow or underflow spuriously).

1 Like

What’s a better implementation?

Edit: Sorry, I just realized this was an old thread.