https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Ankit Shah

12/22/2021, 5:15 PM
Hello everyone, just a small question. In kotlin lets say I do, 
(10/3).toInt()
 it returns 3 but what I want is the upper value i.e. 4. How can I achieve it?
i

Igor Milakovic

12/22/2021, 5:17 PM
Perhaps do the
ceil
of
10/3
before
toInt()
?
a

Ankit Shah

12/22/2021, 5:29 PM
Thanks @Igor Milakovic
👍 1
r

ruitzei

12/22/2021, 5:57 PM
Keep in mind that you’re performing an integer division and you’ll always get an
int
from that, one of the operands should be a
double
or a
float
to get that desired behaviour.
e

elizarov

12/22/2021, 7:35 PM
If you want to round up integer division, then add denominator minus one to the nominator before division, e.g.
(10 + 3 - 1) / 3
1
mind blown 12
r

ruitzei

12/22/2021, 7:51 PM
just make sure
nominator + denominator
doesn’t overflow 😂
d

Diego Rodriguez

12/22/2021, 8:56 PM
you can avoid the overflow doing
1 + (nominator - 1) / denominator
, e.g.
1 + (10 - 1) / 3
👀 1
m

mcpiroman

12/31/2021, 3:36 PM
Maybe there should be a std function - `assertEquals(4, 10 divUp 3)`I have defined it as a util in my project. Example impl:
Copy code
infix fun Int.divUp(denominator: Int) = 1 + (this - 1) / denominator  // delegate handling of division by 0 to the / operator
might need special handling for nevative values though.