Java双精度数保留2位小数

17

我正在尝试将双精度浮点数保留两位小数,但在某些情况下无法正常工作。

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

public static void main(String[] args) {
    System.out.println(round(25.0,2));  //25.0 - expected 25.00
    System.out.println(round(25.00d,2)); //25.0 - expected 25.00
    System.out.println(round(25,2));   //25.0 - expected 25.00
    System.out.println(round(25.666,2));  //25.67
}

简而言之,无论小数是否存在,始终保留值到2位小数,即使需要填充额外的零。

任何帮助都将不胜感激!


3
可能需要使用十进制格式而不是setScale。 - RP-
4个回答

22

你的代码有两件事需要改进。

首先,将double强制转换为BigDecimal以进行四舍五入是一种非常低效的方法。你应该使用Math.round代替:

    double value = 1.125879D;
    double valueRounded = Math.round(value * 100D) / 100D;

其次,在将实数转换为字符串时,您可以考虑使用System.out.printf或String.format进行格式化输出。在您的情况下,使用格式"%.2f"即可。

    System.out.printf("%.2f", valueRounded);

1
如果您需要将数值四舍五入为双精度浮点型,那么“First”部分是必要的。使用适当的精度格式化也能实现正确的四舍五入,因此,如果您的程序最终目标是获取四舍五入后的字符串表示形式,则只需使用String.formatSystem.out.printf即可。 - Aivean
这并不像RoundingMode.HALF_UP那样实现四舍五入。事实上,这根本不是四舍五入,只是截断。 - David Conrad
2
从我的角度来看,这两个示例都是按照RoundingMode.HALF_UP算法工作的。此外,String.format被声明使用该算法(在此处搜索“round half up algorithm”关键字) 。 - Aivean
好的观点。我改正我的错误。 - David Conrad

5
这将对你有用:
public static void main(String[] args) {

    DecimalFormat two = new DecimalFormat("0.00"); //Make new decimal format

    System.out.println(two.format(25.0)); 

    System.out.println(two.format(25.00d));

    System.out.println(two.format(25));

    System.out.println(two.format(25.666));

}

5
我使用String类的format()函数。这是更简单的代码。"%.2f"中的数字2表示您要显示的小数点后位数。"%.2f"中的f表示您正在打印一个浮点数。这是有关格式化字符串的文档(http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
double number = 12.34567;
System.out.println(String.format("%.2f", number));

4
你正在将BigDecimal转换回double,这实际上会删除尾随的零。
你可以返回BigDecimalBigDecimal.toPlainString()
public static String round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.toPlainString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接