use .ceil
math.ceil(x).toInt()
Answer from Tenobaal on Stack OverflowWhat is missing is ceilDiv. Although whether std lib should implement that is still (in discussion), we could implement with the help of floorDiv:
/** Divides this value by the other value, ceiling the result to an integer that is closer to positive infinity. */
fun Int.ceilDiv(other: Int): Int {
return this.floorDiv(other) + this.rem(other).sign.absoluteValue
}
fun main() {
println((-2).ceilDiv(2)) // -1
println((-1).ceilDiv(2)) // 0
println(0.ceilDiv(2)) // 0
println(1.ceilDiv(2)) // 1
println(2.ceilDiv(2)) // 1
println(3.ceilDiv(2)) // 2
println(4.ceilDiv(2)) // 2
println("-----")
println((-2).ceilDiv(-2)) // 1
println((-1).ceilDiv(-2)) // 1
println(0.ceilDiv(-2)) // 0
println(1.ceilDiv(-2)) // 0
println(2.ceilDiv(-2)) // -1
println(3.ceilDiv(-2)) // -1
println(4.ceilDiv(-2)) // -2
}
The simple method for positive integers: fun calc(a: Int, b: Int) = (a + b - 1) / b
No, Math.ceil() won't work on its own because the problem occurs earlier. a and b are both integers, so dividing them evaluates to an integer which is the floor of the actual result of the division. For a = 3 and b = 2, the result is 1. The ceiling of one is also one - hence you won't get the desired result.
You must fix your division first. By casting one of the operands to a floating point number, you get a non-integer result as desired. Then you can use Math.ceil to round it up. This code should work:
Math.ceil((double)a / b);
You can use this expression (assuming a and b are positive)
(a+b-1)/b