我正在尝试找到一种简单的方法来将双精度数转换为两位小数。我使用BigDecimal来做这个技巧,但注意到java.math.BigDecimal类的函数doubleValue
不存在。
以下功能:
fun Double.roundTo2DecimalPlaces() =
BigDecimal(this).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()
给我这个编译错误:
: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版本是1.1.1
答案 0 :(得分:16)
你可以不使用toDouble()
,即:
fun Double.roundTo2DecimalPlaces() =
BigDecimal(this).setScale(2, BigDecimal.ROUND_HALF_UP).toDouble()
答案 1 :(得分:1)
我发现了这个问题,看看如何替换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
}
此方法比转换为BigDecimal
快x20,但在极端示例中遇到浮点不准确。
Assert.assertEquals(4238764872.745398676, 4238764872.745398675983467.toFixed(9), 0.00000000001)
对于上述内容失败,但成功接受了接受的答案(将比例更改为参数)