我知道基于 2 计算的 double 问题:
var total: Double = 0.1
total *= 0.1
total /= 0.1
println(total) // 0.10000000000000002
我知道 BigDecimal 应该用于与货币相关的计算,但在我的情况下,小的精度损失是可以接受的,因为我需要做的所有货币计算是将货币 C1 转换为货币 C2,然后再转换回货币 C1。唯一的问题是,当我以 5 位小数精度向客户显示结果时,转换后的 C1 的两个值应该匹配。
现在我想弄清楚,在最坏的情况下,此转换的值可能会漂移多少?可能导致最坏情况的数字是多少?
最佳答案
您可以阅读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 个小数位,这意味着最多可以达到 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/