0

I want 2 decimals after the comma, also when it's zero. The result has to be a Double.

val price: Double = 32.0
val result = price.toRoundedUpDouble()

private fun Double.toRoundedUpDouble(fraction: Int = 2) =
    BigDecimal(this.toString()).setScale(fraction, RoundingMode.HALF_UP).toDouble()

32.0 becomes 32.0 but should be 32.00

32.4983 becomes 32.5 but should be 32.50

32.40 becomes 32.4 but should be 32.40

Jim Clermonts
  • 1,694
  • 8
  • 39
  • 94
  • It's not a good idea to create a BigDecimal from a Double; if the number's not an exact binary fraction, Double can't store it exactly, and so the Double value will have been rounded; BigDecimal will then have to try to round that to a _decimal_ fraction — which might not end up with the original value you wanted.  (See [this question](/questions/588004).  This example starts with an exact integer, so doesn't show the problem.) Always better to start with an integer or String. – gidds Jun 30 '21 at 11:57
  • And if you're formatting this for output, usually better to use a [`DecimalFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html) than a BigDecimal anyway. – gidds Jun 30 '21 at 11:58

1 Answers1

0

This should do the trick:

fun Double.toRoundedUpDouble(fraction: Int = 2) = run {
     val pow10 = 10.0.pow(fraction)
     floor(this * pow10) / pow10
}.toString().let { if (it.split(".")[1].length < 2) "${it}0" else it }
Gieted
  • 835
  • 6
  • 21