Kotlin BigDecimal 乘法错误结果

发布于 2025-01-13 14:02:43 字数 360 浏览 4 评论 0原文

我需要使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

向日葵 2025-01-20 14:02:43

该问题可能与 fee BigDecimal 的构造有关。这是获取一个 double 值并将其转换为 BigDecimal。不幸的是,一些相当简单的十进制分数不可能精确地表示为 double 或 float ,并且 BigDecimal 的这个构造函数将采用不精确的< code>double 作为其值。

来自文档

此构造函数的结果可能有些不可预测。人们可能会认为在 Java 中编写 new BigDecimal(0.1) 会创建一个完全等于 0.1(未缩放的值 1,小数位数为 1)的 BigDecimal,但它实际上等于 0.1000000000000000055511151231257827021181583404541015625。这是因为 0.1 不能精确地表示为 double(或者就此而言,表示为任何有限长度的二进制分数)。因此,无论表面如何,传递给构造函数的值并不完全等于 0.1。

解决这个问题的方法是使用 String 构造函数,它可以解决必须“通过”double 进行转换的问题。

The issue is likely to be with the construction of the fee BigDecimal. This is taking a double value and converting it to a BigDecimal. Unfortunately, some fairly simple decimal fractions are impossible to precisely represent as doubles or floats, and this constructor for BigDecimal will take that imprecise double as its value.

From the documentation:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

The way around this is to use the String constructor, which gets round the issue of having to convert "via" a double.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文