Rounding up a number to nearest multiple of 5

后端 未结 21 1994
感动是毒
感动是毒 2020-11-27 15:24

Does anyone know how to round up a number to its nearest multiple of 5? I found an algorithm to round it to the nearest multiple of 10 but I can\'t find this one.

T

21条回答
  •  旧巷少年郎
    2020-11-27 16:08

    This Kotlin function rounds a given value 'x' to the closest multiple of 'n'

    fun roundXN(x: Long, n: Long): Long {
        require(n > 0) { "n(${n}) is not greater than 0."}
    
        return if (x >= 0)
            ((x + (n / 2.0)) / n).toLong() * n
        else
            ((x - (n / 2.0)) / n).toLong() * n
    }
    
    fun main() {
        println(roundXN(121,4))
    }
    

    Output: 120

提交回复
热议问题