我同意
jmcnamara’s prior answer.这个答案扩展了.
对于每个IEEE 754 64位二进制浮点数,在输入时存在一定数量的小数点.从-130.98999999999069开始,最接近的可表示值为-130.98999999999068677425384521484375.在一轮到最接近一半的偶数规则下,任何范围[-130.98999999998807009851085604168474674224853515625,-130.9899999999906725633991300128400325775146484375]回合到该值. (范围是关闭的,因为中心数字的二进制表示是偶数,如果是奇数,范围将被打开). -130.98999999999069和-130.9899999999907都在范围内.
你有与Excel相同的浮点数.
您确实有与输入到Excel相同的浮点数.不幸的是,进一步的实验表明,Excel 2007只是转换您输入的最显着的15位数字.我将-130.98999999999069粘贴到Excel单元格中.不仅显示为-130.98999999999,算术使用它与该值最接近的一倍-130.989999999990004653227515518665313720703125,而不是原始输入.
要获得与Excel相同的效果,您可能需要使用例如BigDecimal要截断到15位十进制数字,然后转换为double.
Java的浮点值的默认字符串转换基本上选择小数位数,将最小的位数转换回原始值. -130.9899999999907的小数位数比-130.98999999999069少.显然,Excel显示的数字较少,但Apache POI正在获得与Java中相同数量的表示之一.
这是我在这个答案中用来获取数字的程序.请注意,我仅使用BigDecimal来获得双打的确切打印输出,并计算两个连续双打之间的中点.
import java.math.BigDecimal;
class Test {
public static void main(String[] args) {
double d = -130.98999999999069;
BigDecimal dDec = new BigDecimal(d);
System.out.println("Printed as double: "+d);
BigDecimal down = new BigDecimal(Math.nextAfter(d, Double.NEGATIVE_INFINITY));
System.out.println("Next down: " + down);
System.out.println("Half down: " + down.add(dDec).divide(BigDecimal.valueOf(2)));
System.out.println("Original: " + dDec);
BigDecimal up = new BigDecimal(Math.nextAfter(d, Double.POSITIVE_INFINITY));
System.out.println("Half up: " + up.add(dDec).divide(BigDecimal.valueOf(2)));
System.out.println("Next up: " + up);
System.out.println("Original in hex: "+Long.toHexString(Double.doubleToLongBits(d)));
}
}
这是它的输出:
Printed as double: -130.9899999999907
Next down: -130.989999999990715195963275618851184844970703125
Half down: -130.9899999999907009851085604168474674224853515625
Original: -130.98999999999068677425384521484375
Half up: -130.9899999999906725633991300128400325775146484375
Next up: -130.989999999990658352544414810836315155029296875
Original in hex: c0605fae147ae000