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.
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
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