Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round negative integer quotient towards negative infinity

Tags:

rounding

swift

It appears that integer divisions in Swift round towards zero rather than towards the lower number. This means, for instance, that -1 / 2 will be 0 instead of -1.

Is there a way to tell Swift to round towards the lower number? I know how I can "simulate" it, but if there's a native solution, I'd rather use it.

like image 553
zneak Avatar asked Sep 16 '14 03:09

zneak


1 Answers

You can define your own operator like this:

infix operator </> { associativity left }
func </> (a: Int, b: Int) -> Int {
    return Int(floor(Double(a) / Double(b)))
}

so that you don't have to type that absurd expression. I'm proposing </>, but of course you can choose your own.

If you don't like creating operators, then use it as a normal function:

func div (a: Int, b: Int) -> Int {
    return Int(floor(Double(a) / Double(b)))
}

Last, but personally I would not use it, you can redefine the division operator:

func / (a: Int, b: Int) -> Int {
    return Int(floor(Double(a) / Double(b)))
}

and in that case it will applied to all divisions - be aware of side effects though

like image 89
Antonio Avatar answered Sep 30 '22 21:09

Antonio