Let's say I have an integer like 588 and I want to round that number up to 590
Or:
397 -> 400,
233 -> 230
...
Or maybe:
388 -> 400
77 -> 100
Does Kotlin has a function for these kind of situations? Or do I need to create my own algorithm for that? I tried using ceil()
or roundToInt()
but I think those are just for rounding doubles.
CodePudding user response:
You're doing arbitrary rounding, so no there's nothing like that built in - only functions for rounding to the nearest integer in various ways.
You could write a basic rounding function like this:
fun Int.roundToClosest(step: Int): Int {
require(step > 0)
// in this case 'lower' meaning 'closer to zero'
val lower = this - (this % step)
val upper = lower if (this >= 0) step else -step
return if (this - lower < upper - this) lower else upper
}
println(-5.roundToClosest(10))
>> -10
In this case it "rounds up" away from zero, so for negative numbers it increases their magnitude instead of rounding up towards positive infinity. If you want ceil
behaviour (rounding to positive infinity) I'll leave that as an exercise for the reader!