I am trying to find a simple way to round a double to two decimal places. I am using a BigDecimal to do the trick but noticed that the function doubleValue
of the java.math.BigDecimal class does not exist.
The following function:
fun Double.roundTo2DecimalPlaces() =
BigDecimal(this).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()
Is giving me this compile error:
:compileKotlin
Using kotlin incremental compilation
w: The '-d' option with a directory destination is ignored because '-module' is specified
e: -{FilePathAndNameWereHere}-: (20, 14): Unresolved reference: doubleValue
:compileKotlin FAILED
Kotlin version is 1.1.1
can you not use toDouble()
instead, ie:
fun Double.roundTo2DecimalPlaces() =
BigDecimal(this).setScale(2, BigDecimal.ROUND_HALF_UP).toDouble()
I found this question looking how to replace Javascript `toFixed(n)'
fun Double.toFixed(s : Int): Double {
if (s==0) return round(this)
val power = (10.0).pow(s)
return round(this * power)/power
}
This method is x20 faster than converting to a BigDecimal
but suffers from floating point inaccuracy in extreme examples.
Assert.assertEquals(4238764872.745398676, 4238764872.745398675983467.toFixed(9), 0.00000000001)
fails for the above, but succeeds for the accepted answer (changing the scale to a parameter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With