Java Double总结为2位小数

Red*_*ddy 14 java decimal rounding

我试图将双值舍入为2位小数,但它并不适用于所有情况

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
}
Run Code Online (Sandbox Code Playgroud)

简而言之,无论十进制是否存在,即使需要填充额外的零,也始终保持最多2位小数.

任何帮助表示赞赏!

Aiv*_*ean 18

您的代码中有两件事可以改进.

首先,向BigDecimal强制转换为圆形它是非常低效的方法.您应该使用Math.round代替:

    double value = 1.125879D;
    double valueRounded = Math.round(value * 100D) / 100D;
Run Code Online (Sandbox Code Playgroud)

其次,当您打印或将实数转换为字符串时,您可以考虑使用System.out.printf或String.format.在你的情况下,使用格式"%.2f"就可以了.

    System.out.printf("%.2f", valueRounded);
Run Code Online (Sandbox Code Playgroud)

  • @DavidConrad从我的角度来看,这两个例子都是根据RoundingMode.HALF_UP算法工作的.此外,String.format [声明使用此算法](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax)(搜索'round half up algorithm'关键字). (2认同)

Duc*_*cRP 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));
Run Code Online (Sandbox Code Playgroud)


小智 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));

}
Run Code Online (Sandbox Code Playgroud)