1

I would like to round Double variables to the next lower 0.5 value. For instance

12.03 -> 12

12.44 -> 12

12.56 -> 12.5

12.99 -> 12.5

There should be an elegant easy Kotlin like way?

Pavel Pipovic
  • 339
  • 1
  • 3
  • 12
  • Note that, due to [the way floating-point values work](https://stackoverflow.com/questions/588004/is-floating-point-math-broken), the result will probably not be _exactly_ what you expect…  If you need an exact value, use another format (such as `BigDecimal`, or scaled integers). – gidds Sep 10 '20 at 16:20

1 Answers1

4

Multiply by 2, take the floor, then divide by 2 again.

There doesn't seem to be a built-in way, but you can always write it yourself:

fun Double.roundDownToMultipleOf(base: Double): Double = base * floor(this / base)

Use as 12.56.roundDownToMultipleOf(0.5).

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Works perfect thanks. I was looking for smt like this. How could I leave 12.5 but print 12.0 as 12 straight? – Pavel Pipovic Sep 10 '20 at 15:30
  • 1
    @PavelPipovic Not so easy anymore but you could make your own method: `fun Double.format() = if (this == toInt().toDouble()) toInt().toString() else toString()` which you then can use like `12.5.format()` or like `12.0.format()` which will return `12.5` resp. `12` – Lino Sep 10 '20 at 15:41