为什么 HALF_UP 有时会用双舍入? [英] Why does HALF_UP sometimes round down with double?

查看:67
本文介绍了为什么 HALF_UP 有时会用双舍入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

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 ) );

产生结果(实时代码):

          : double  float  
toString  : 1713.6  1713.6 
DOWN      : 1713    1713   
HALF_DOWN : 1714    1714   
HALF_UP   : 1713    1714   <--- notice this line
UP        : 1714    1714   

我知道某些数字不能完全表示为浮点数.1713.6 的实际浮点表示为 1713.5999755859375(请参阅此页面).

I know that certain numbers cannot be represented exactly as floating-point numbers. The actual floating-point representation for 1713.6 is 1713.5999755859375 (see this page).

但是为什么在这种情况下HALF_UP要向下舍入?

But why does HALF_UP round down in this case?

使用 Java 1.8u25

Using Java 1.8u25

推荐答案

Java 8 中存在一个关于 NumberFormat 和 RoundingMod HALF_UP 的错误,请参阅 8039915.这已通过 8u40 修复(发行说明).

There was a bug in Java 8 regarding the NumberFormat and RoundingMod HALF_UP see 8039915. This was fixed with 8u40 (Release Notes).

这篇关于为什么 HALF_UP 有时会用双舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆