2015-06-04 22 views
10

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

+1

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

+0

In 1713 trên JDK 1.8b25, 64 bit, Linux. –

Trả lời

14

Có một lỗi trong Java 8 về NumberFormat và RoundingMod HALF_UP thấy 8039915. Điều này đã được sửa với 8u40 (Release Notes).

1

Ideone đang sử dụng ánh nắng mặt trời-jdk-8u25 nơi hành vi lỗi này xuất hiện.

Trên Java 1.7, tôi nhận được HALF_UP: 1714 1714 đúng.

enum RoundingMode - Chỉ định hành vi làm tròn cho các phép toán số có khả năng loại bỏ độ chính xác.

See Oracle javadoc: Result of rounding input to one digit with the given rounding mode[Rounding Mode Table]

+0

Làm tròn bảng hữu ích để hiểu kết quả của hoạt động RoundingMode.x. – Rajesh

Các vấn đề liên quan