Kotlin如何实现整数按指定位数向上取整?需自定义算法吗?
Kotlin整数按指定步长取整的实现方法
Kotlin标准库并没有直接提供整数按自定义步长(比如10、100)取整的内置函数,得自己写算法来处理。针对你提到的几种场景,下面给出具体实现:
向上取整到指定步长的倍数
像588→590(步长10)、397→400(步长100)、388→400(步长100)这类需求,可以用这个扩展函数:
fun Int.ceilToStep(step: Int): Int { require(step > 0) { "步长必须大于0" } return if (this % step == 0) this else this + step - this % step } // 调用示例 println(588.ceilToStep(10)) // 输出590 println(397.ceilToStep(100)) // 输出400 println(388.ceilToStep(100)) // 输出400
向下取整到指定步长的倍数
比如233→230(步长10)这种向下取整的场景,实现如下:
fun Int.floorToStep(step: Int): Int { require(step > 0) { "步长必须大于0" } return this - this % step } // 调用示例 println(233.floorToStep(10)) // 输出230 println(77.floorToStep(100)) // 输出0
四舍五入到指定步长的倍数
如果需要类似常规四舍五入的逻辑(比如237→240、77→100),可以用这个函数:
fun Int.roundToStep(step: Int): Int { require(step > 0) { "步长必须大于0" } val remainder = this % step return if (remainder >= step / 2) this + step - remainder else this - remainder } // 调用示例 println(233.roundToStep(10)) // 输出230 println(237.roundToStep(10)) // 输出240 println(77.roundToStep(100)) // 输出100
你之前尝试的ceil()和roundToInt()确实主要针对Double类型,虽然可以先把整数转成Double计算再转回Int,但这种方式对大整数可能存在精度问题,不如直接用整数运算的实现靠谱。
内容的提问来源于stack exchange,提问作者user17121955
相关产品推荐
相关产品推荐

