在 Kotlin 中使用 RoundingMode HALF_UP 不添加舍入数时舍入错误

时间:2021-06-17 13:31:30

标签: kotlin

考虑以下方法:

fun main() {
    var costs = 0
    var transactionFee = 1.325

    var total = (costs + transactionFee).toRoundedUpDouble()
}

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

我想要一个逗号后有 2 个小数的数字,从 5 向上取整。例如1.325 变成 1.33。这在我添加整数时有效,但在我不添加时无效:

输出:

5.00 + 1.325 becomes 6.33 = good
5 + 1.325 becomes 6.33 = good
1 + 1.325 becomes 2.33 = good

1.325 becomes 1.32 = NOT GOOD
0 + 1.325 becomes 1.32 = NOT GOOD 
0.00 + 1.325 becomes 1.32 = NOT GOOD 
0.000 + 1.325 becomes 1.32 = NOT GOOD 

This thread 没有回答我的问题。

1 个答案:

答案 0 :(得分:3)

你说 this thread 没有回答你的问题,但我确实回答了。

如该线程中所述,双重文字对您撒谎,println 也是如此。 要了解这些文字给您的实际值,您可以这样使用 BigDecimal

println(BigDecimal(1.325))     // 1.3249999999999999555910790149937383830547332763671875
println(BigDecimal(0 + 1.325)) // 1.3249999999999999555910790149937383830547332763671875
println(BigDecimal(5 + 1.325)) // 6.32500000000000017763568394002504646778106689453125

如果您想要准确的结果,请从一开始就使用 BigDecimal,并确保使用字符串初始化它们,而不是双重文字:

fun main() {
    var costs = BigDecimal.ZERO
    var transactionFee = BigDecimal("1.325")

    var total = (costs + transactionFee).roundedUp()
    println(total) // 1.33
    println(total.toDouble()) // 1.33
}

fun BigDecimal.roundedUp(fraction: Int = 2) = setScale(fraction, RoundingMode.HALF_UP)