Kotlin BigDecimal 乘法错误结果
我需要使用 BigDecimal 进行一些计算,但对这种行为感到有点惊讶:
val thousand = BigDecimal(1000)
val fee = BigDecimal(0.005)
println(thousand * fee)
您希望控制台包含 5
但结果是 5.000000000000000104083408558608425664715468883514404296875000
我知道我可以限制精度并做使用 setScale
进行一些舍入,但真正的问题是为什么首先需要这样做。这个结果显然是错误的。
我缺少什么?
I need to use BigDecimal for some computation but am a bit surprised by the behaviour:
val thousand = BigDecimal(1000)
val fee = BigDecimal(0.005)
println(thousand * fee)
You'd expect the console to contain 5
but the result is 5.000000000000000104083408558608425664715468883514404296875000
I know that I can limit the precision and do some rounding with setScale
but the real question is Why is this needed in the first place. This result is obviously wrong.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该问题可能与
fee
BigDecimal 的构造有关。这是获取一个 double 值并将其转换为 BigDecimal。不幸的是,一些相当简单的十进制分数不可能精确地表示为 double 或 float ,并且 BigDecimal 的这个构造函数将采用不精确的< code>double 作为其值。来自文档 :
解决这个问题的方法是使用 String 构造函数,它可以解决必须“通过”double 进行转换的问题。
The issue is likely to be with the construction of the
fee
BigDecimal. This is taking adouble
value and converting it to aBigDecimal
. Unfortunately, some fairly simple decimal fractions are impossible to precisely represent asdouble
s orfloat
s, and this constructor forBigDecimal
will take that imprecisedouble
as its value.From the documentation:
The way around this is to use the String constructor, which gets round the issue of having to convert "via" a
double
.