Search code examples
kotlinmathintegerdivision

Kotlin: FInd closest divisible


Is there function in kotlin stdlib to get closest divisible number like this: fun closestDivisible(initialValue: Number, divisibleBy: Int)


Solution

  • There is no predefined function but there is a solution:

    fun closestDivisible(initialValue: Int, divisibleBy: Int): Number {
        val quotient = initialValue.toDouble() / divisibleBy
        val floor = floor(quotient).toInt()
        val ceil = ceil(quotient).toInt()
        return when {
            (initialValue - floor * divisibleBy) < (ceil * divisibleBy - initialValue) -> floor * divisibleBy
            else -> ceil * divisibleBy
        }
    }
    

    This function returns the closest number that is divisible by 'divisibleBy'.