Search code examples
javakotlincountrangebigdecimal

Kotlin BigDecimal range with custom step


I have a string "1;5;0.5" it means BigDecimal range 1..5 with step 0.5. So, i have to convert it into a kotlin range, and count elements. do something like this:

val str = "1;5;0.5"
var (from, to, st) = str.split(";").map { it.toBigDecimal() }
val numbersWithStep = (from..to step st).count()

But it doesn't work. It works only with int numbers. There is any more simple way to count elements instead of using while cycle?


Solution

  • You mean, like a really simple math?

    (to - from) / st + 1
    

    Just note that division has to be done with rounding down. A working example for BigDecimals would be:

    (to - from).divideToIntegralValue(st) + BigDecimal.ONE
    

    You may need to check for to < from if this is your case.