gpt4 book ai didi

java - 如果您使用 double 将货币值转换为另一种货币并返回,您可能会损失的最精确度是多少?

转载 作者:行者123 更新时间:2023-11-30 06:12:53 24 4
gpt4 key购买 nike

我知道基于 2 计算的 double 问题:

var total: Double = 0.1
total *= 0.1
total /= 0.1
println(total) // 0.10000000000000002

我知道 BigDecimal 应该用于与货币相关的计算,但在我的情况下,小的精度损失是可以接受的,因为我需要做的所有货币计算都是将货币 C1 转换为货币 C2,然后再转换回货币 C1。唯一的问题是当我以 5 位小数精度向客户显示结果时,此转换后 C1 的两个值应该匹配。

现在我想弄清楚,在最坏的情况下,此转换的值(value)可能会漂移多少?可能导致最坏情况的数字是多少?

最佳答案

您可以阅读 double-precision floating-point 的描述:

The 11 bit width of the exponent allows the representation of numbers with a decimal exponent between 10^−308 and 10^308, with full 15–17 decimal digits precision.

由于您需要 5 个小数位数,这意味着您可以达到最大值。 10位整数。

或者你可以测试一下。有时经验证据更有说服力:

double value = 0.00009;
while (true) {
String nextDown = String.format("%.5f", Math.nextDown(value));
String nextUp = String.format("%.5f", Math.nextUp(value));
if (! nextDown.equals(nextUp))
break; // loss of precision to 5 decimals
System.out.printf("Good: %.5f%n", value);
value = value * 10 + 0.00009;
}
System.out.printf("Bad: %.5f%n", value);

输出

Good: 0.00009
Good: 0.00099
Good: 0.00999
Good: 0.09999
Good: 0.99999
Good: 9.99999
Good: 99.99999
Good: 999.99999
Good: 9999.99999
Good: 99999.99999
Good: 999999.99999
Good: 9999999.99999
Good: 99999999.99999
Good: 999999999.99999
Good: 9999999999.99999
Bad: 99999999999.99997

是的,10 分好,11 分差。

关于java - 如果您使用 double 将货币值转换为另一种货币并返回,您可能会损失的最精确度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32404995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com