Các mã sau đây:Tại sao đôi khi HALF_UP tròn xuống gấp đôi?
double doubleValue = 1713.6;
float floatValue = 1713.6f;
String fs = "%-9s : %-7s %-7s\n";
System.out.printf(fs, "", "double", "float");
DecimalFormat format = new DecimalFormat("#0");
System.out.printf(fs, "toString", String.valueOf(doubleValue), String.valueOf(floatValue));
format.setRoundingMode(RoundingMode.DOWN);
System.out.printf(fs, "DOWN", format.format(doubleValue), format.format(floatValue));
format.setRoundingMode(RoundingMode.HALF_DOWN);
System.out.printf(fs, "HALF_DOWN", format.format(doubleValue), format.format(floatValue));
format.setRoundingMode(RoundingMode.HALF_UP);
System.out.printf(fs, "HALF_UP", format.format(doubleValue), format.format(floatValue));
format.setRoundingMode(RoundingMode.UP);
System.out.printf(fs, "UP", format.format(doubleValue), format.format(floatValue));
Tạo kết quả (live code):
: double float
toString : 1713.6 1713.6
DOWN : 1713 1713
HALF_DOWN : 1714 1714
HALF_UP : 1713 1714 <--- notice this line
UP : 1714 1714
Tôi biết rằng con số nhất định không thể được đại diện chính xác như số dấu chấm động. Biểu diễn dấu phẩy động thực tế cho 1713.6 là 1713.5999755859375 (xem this page).
Nhưng tại sao HALF_UP vòng xuống trong trường hợp này?
Sử dụng Java 1.8u25
Phiên bản Java nào và nền tảng nào? Nó in 1714 trên máy tính của tôi, cả trong Java 1.7 và Java 1.8. – RealSkeptic
In 1713 trên JDK 1.8b25, 64 bit, Linux. –