以下代码:
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( floatValue ) ); format.setRoundingMode( RoundingMode.HALF_UP ); System.out.printf( fs,"HALF_UP",format.format( floatValue ) ); format.setRoundingMode( RoundingMode.UP ); System.out.printf( fs,"UP",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