在 Kotlin 中,BigDecimal 除法返回奇怪的结果。
BigDecimal(1.0) / BigDecimal(2.0)
// returns 0.0
// Just like Int(1) / Int(2) returns 0
但是:
BigDecimal(1.1) / BigDecimal(2.0)
// returns 0.55
// Just like Double(1.1) / Double(2.0) returns 0.55
那么为什么会发生这种情况,我怎样才能使 1.0/2.0
在不使用 divide()
给出比例参数的情况下使用 BigDecimal 返回 0.5?
更新:
完整代码如下:
Welcome to Kotlin version 1.2.41 (JRE 1.8.0_172-b11)
Type :help for help, :quit for quit
>>> import java.math.BigDecimal
>>> BigDecimal(1.0) / BigDecimal(2.0)
0
>>> BigDecimal(1.1) / BigDecimal(2.0)
0.550000000000000044408920985006261616945266723632812
更新 2:
根据@user2864740
BigDecimal(1.0).divide(BigDecimal(2.0))
// returns 0.5
和
BigDecimal("1.0") / BigDecimal(2.0)
// returns 0.5
因此结果令人困惑。对于 BigDecimals,为什么 1.0/2.0
返回 0.0,1.0.divide(2.0)
返回 0.5,而 "1.0"/2.0
返回 0.5?
最佳答案
如果你写divide
明确地,它将以与 Java 中相同的方式工作:
val a = BigDecimal(1.0)
val b = BigDecimal(2.0)
val x = a.divide(b) // 0.5
当您使用 /
运算符时,它会转换为 BigDecimal.div
来自标准库的扩展,它执行以下操作:
Enables the use of the / operator for BigDecimal instances.
The scale of the result is the same as the scale of this (divident), and for rounding the RoundingMode.HALF_EVEN rounding mode is used.
您可以看看不同的 RoundingMode
常量是如何工作的 here .
关于java.math.BigDecimal 除法不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51718960/