Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal.doubleValue does not exist?

Tags:

android

kotlin

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

like image 981
Dave Thomas Avatar asked Aug 26 '17 00:08

Dave Thomas


2 Answers

can you not use toDouble() instead, ie:

fun Double.roundTo2DecimalPlaces() =
    BigDecimal(this).setScale(2, BigDecimal.ROUND_HALF_UP).toDouble()
like image 177
homerman Avatar answered Oct 17 '22 06:10

homerman


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)

like image 21
Simon Featherstone Avatar answered Oct 17 '22 04:10

Simon Featherstone