Home » Android » android – BigDecimal.doubleValue does not exist?

android – BigDecimal.doubleValue does not exist?

Posted by: admin June 15, 2020 Leave a comment


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:

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

How to&Answers:

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)