Java 8:具有HALF_UP舍入模式的DecimalFormat

时间:2017-08-03 09:08:51

标签: java rounding decimalformat

以下测试失败:

@Test
public void testRound() throws Exception {
    double v = 0.015d;
    DecimalFormat format = new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.US));
    format.setRoundingMode(RoundingMode.HALF_UP);
    assertEquals("0.02", format.format(v));
}

我发现Java 7Java 8已经解决了问题,但在“jdk1.8.0_144”上它仍然无效:

junit.framework.ComparisonFailure: null 
Expected :0.02
Actual   :0.01 

1 个答案:

答案 0 :(得分:0)

使用此:

DecimalFormat format = new DecimalFormat("#.###", new DecimalFormatSymbols(Locale.US));