is there a better way to divide ints and round dow...
# announcements
b
is there a better way to divide ints and round down to an int than this
Copy code
floor(int1.toDouble() / int2).toInt()
v
Why don't you simply do an integer division?
int1 / int2
Copy code
fun main() {
    val three: Int = 3
    val two: Int = 2
    println(three / two)
}
results in printing
1
r
Just to be clear, int division always rounds down:
9/5 == 1
b
thanks, types required in floor probably confused me
and I wasn’t sure if there was something like / and // in python
v
You mean
-1
I guess @Rob Elliot , but there indeed is a difference, the snippet of Bernhard gives
-2
What do
/
and
//
in Python do?
r
I’d left a space after the hyphen, but I’ve clarified it now
v
Well, for negative numbers it is indeed different. Original snippet with
floor
always rounds towards negative infinity. Pure integer division always rounds towards
0
r
Good point, big difference.
v
And also different from Python, there
/
as integer division rounds towards negative infinity if https://www.geeksforgeeks.org/division-operator-in-python/ is correct and
//
does the same even for floating point numbers where
/
would do proper division.
So I guess you actually need to use
floor
to get the same result as with Python
/
if negative numbers are involved and to get the same result as with Python
//
.
157 Views