【发布时间】:2014-05-25 09:20:04
【问题描述】:
我对 Java 的 NumberFormat 的行为感到困惑。
考虑以下将双精度值转换为其百分比表示并将所得百分比四舍五入到小数点后三位的方法:
public static String doubleToPercent(final double val) {
NumberFormat nf = NumberFormat.getPercentInstance();
// Default rounding mode is HALF_EVEN
nf.setRoundingMode(RoundingMode.HALF_UP);
nf.setMaximumFractionDigits(3);
return nf.format(val);
}
舍入模式为HALF_UP。
worksAsExpected 中的结果并不让我感到惊讶;测试通过:
@Test
public void worksAsExpected() {
double input = 1.234585;
String expected = "123.459%";
String output = doubleToPercent(input);
assertEquals(expected, output);
}
但是这个呢:
@Test
public void surprise() {
double input = 1.234535;
String expected = "123.454%";
String output = doubleToPercent(input);
assertEquals(expected, output);
}
为什么这个测试失败了?为什么1.234535 向下取整,而1.234585 向上取整?
另一方面,如果最后一位数字是6,则该数字向上取整。
@Test
public void noSurprise() {
double input = 1.234536;
String expected = "123.454%";
String output = doubleToPercent(input);
assertEquals(expected, output);
}
这与double 的精度限制有关吗?我猜想1.234535 这样的数字完全在double 的能力范围内。
我在 Java 1.7.0_51 上运行 Windows 7 x86。
感谢任何见解。
【问题讨论】:
标签: java double number-formatting