當我用HALF_EVEN模式舍入了一個雙精度數時,我發現了一個問題,我不知道它是否是JDK的一個bug?請看下面的代碼:是Java RoundingMode.HALF_EVEN錯誤?
public static void main(String[] args) {
RoundingMode mode = RoundingMode.HALF_EVEN;
for (int i = 10; i < 100; i++) {
double d = i + 0.55;
int scale = 1;
process(d, scale++, mode);
d = i + 0.555;
process(d, scale++, mode);
d = i + 0.5555;
process(d, scale++, mode);
d = i + 0.55555;
process(d, scale++, mode);
System.out.println("\n");
}
}
private static void process(double d, int scale, RoundingMode roundingMode) {
BigDecimal b = new BigDecimal(d).setScale(scale, roundingMode);
System.out.println(d + " -> " + b);
}
我期望輸出:
10.55 -> 10.6
10.555 -> 10.56
10.5555 -> 10.556
10.55555 -> 10.5556
11.55 -> 11.6
11.555 -> 11.56
11.5555 -> 11.556
11.55555 -> 11.5556
.....
但實際上,它輸出數據,如下面的:
10.55 -> 10.6
10.555 -> 10.55
10.5555 -> 10.556
10.55555 -> 10.5556
11.55 -> 11.6
11.555 -> 11.55
11.5555 -> 11.556
11.55555 -> 11.5556
....
30.55 -> 30.6
30.555 -> 30.55
30.5555 -> 30.555
30.55555 -> 30.5556
31.55 -> 31.6
31.555 -> 31.55
31.5555 -> 31.555
31.55555 -> 31.5556
32.55 -> 32.5
32.555 -> 32.55
32.5555 -> 32.556
32.55555 -> 32.5555
33.55 -> 33.5
33.555 -> 33.55
33.5555 -> 33.556
33.55555 -> 33.5555
.........
62.55 -> 62.5
62.555 -> 62.55
62.5555 -> 62.556
62.55555 -> 62.5555
63.55 -> 63.5
63.555 -> 63.55
63.5555 -> 63.556
63.55555 -> 63.5555
64.55 -> 64.5
64.555 -> 64.56
64.5555 -> 64.555
64.55555 -> 64.5555
65.55 -> 65.5
65.555 -> 65.56
65.5555 -> 65.555
65.55555 -> 65.5555
66.55 -> 66.5
66.555 -> 66.56
66.5555 -> 66.555
66.55555 -> 66.5555
有同樣的結果在JDK 1.7 /1.8
這是JDK的bug嗎?
爲什麼你認爲這是一個bug?爲什麼要將BigDecimals加入這個? – Shark