Search code examples
kotlin

Kotlin idiomatic way to round up integer division


If the remainder of an integer division is not zero, I want to proceed with the result rounded up.

Examples:

  • 5 / 2 yields 2. But I want to move on with 3 (integer).
  • 4 / 2 yields 2, which is fine for my use case.

I currently resort to this clunky construct:

ceil(5 / 2.toDouble()).toInt()

example on Kotlin playground: https://pl.kotl.in/eX0rYXnsH

Is there a more idiomatic way to achieve this?


Solution

  • What 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
    }