为什么 HALF_UP 有时会四舍五入?
Why does HALF_UP sometimes round down with double?
以下代码:
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 ) );
产生结果(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
我知道某些数字不能完全表示为浮点数。 1713.6 的实际浮点表示形式是 1713.5999755859375(参见 this page)。
但是为什么在这种情况下HALF_UP会向下?
使用 Java 1.8u25
Ideone 正在使用 sun-jdk-8u25,其中出现了此错误行为。
在 Java 1.7 上,我得到 HALF_UP : 1714 1714 这是正确的。
enum RoundingMode - 指定能够舍弃精度的数值运算的舍入行为。
Java 8 中存在一个关于 NumberFormat 和 RoundingMod 的错误 HALF_UP 请参阅 8039915. This was fixed with 8u40 (Release Notes)。
以下代码:
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 ) );
产生结果(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
我知道某些数字不能完全表示为浮点数。 1713.6 的实际浮点表示形式是 1713.5999755859375(参见 this page)。
但是为什么在这种情况下HALF_UP会向下?
使用 Java 1.8u25
Ideone 正在使用 sun-jdk-8u25,其中出现了此错误行为。
在 Java 1.7 上,我得到 HALF_UP : 1714 1714 这是正确的。
enum RoundingMode - 指定能够舍弃精度的数值运算的舍入行为。
Java 8 中存在一个关于 NumberFormat 和 RoundingMod 的错误 HALF_UP 请参阅 8039915. This was fixed with 8u40 (Release Notes)。