java.math.BigDecimal 除法不准确

标签 java kotlin bigdecimal

在 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/

相关文章:

Android Studio 分析无穷大

java - 解析流函数中的对象

java - 使用 Streams 将 BigDecimals 相加

java - 如何使用 Selenium 点击特定链接?

java - 为什么在这种特定情况下 Autowiring 为空?

java - JDBI支持不带out参数的存储过程

kotlin - 如何在 TeamCity 的 Kotlin DSL 中引用全局表达式?

generics - 使用 "any of"而不是 "all of"的 Kotlin 通用约束

java - 获取存储的实际数字

java - 如何仅在构建后运行 junit 测试?