System.out.println(d)
將經歷Double.toString
這是一個相當複雜的方法(如其文檔中所見),並不總是像您期望的那樣行事。它基本上給出了唯一確定d
的最短字符串。
也許這程序的輸出闡明此:
double[] tests = {
0.49999999999999990d, //output 0.4999999999999999 as expected
0.49999999999999991d, //output 0.4999999999999999
0.49999999999999992d, //output 0.49999999999999994
0.49999999999999993d, //output 0.49999999999999994
0.49999999999999994d, //output 0.49999999999999994 as expected
0.49999999999999995d, //output 0.49999999999999994
0.49999999999999996d, //output 0.49999999999999994
0.49999999999999997d, //output 0.49999999999999994
0.49999999999999998d, //output 0.5
};
String[] literals = {
"0.49999999999999990d",
"0.49999999999999991d",
"0.49999999999999992d",
"0.49999999999999993d",
"0.49999999999999994d",
"0.49999999999999995d",
"0.49999999999999996d",
"0.49999999999999997d",
"0.49999999999999998d",
};
String f = "%-25s%-65s%-25s%n";
System.out.printf(f, "Literal", "Actually represents", "Printed as");
for (int i = 0; i < tests.length; i++)
System.out.printf(f, literals[i],
new BigDecimal(tests[i]).toString(),
Double.valueOf(tests[i]));
輸出:
Literal Actually represents Printed as
0.49999999999999990d 0.49999999999999988897769753748434595763683319091796875 0.4999999999999999
0.49999999999999991d 0.49999999999999988897769753748434595763683319091796875 0.4999999999999999
0.49999999999999992d 0.499999999999999944488848768742172978818416595458984375 0.49999999999999994
0.49999999999999993d 0.499999999999999944488848768742172978818416595458984375 0.49999999999999994
0.49999999999999994d 0.499999999999999944488848768742172978818416595458984375 0.49999999999999994
0.49999999999999995d 0.499999999999999944488848768742172978818416595458984375 0.49999999999999994
0.49999999999999996d 0.499999999999999944488848768742172978818416595458984375 0.49999999999999994
0.49999999999999997d 0.499999999999999944488848768742172978818416595458984375 0.49999999999999994
0.49999999999999998d 0.5 0.5
如可以看到的,在文字有時也從它實際上代表的值遠,這意味着那Double.toString
打印可能看起來令人驚訝的東西。
[在java中保留精度與雙精度]的可能重複(http://stackoverflow.com/questions/322749/retain-precision-with-doubles-in-java) – 2012-03-29 11:41:17