这个问题在这里已有答案:
我试图将双值舍入为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
}
简而言之,无论十进制是否存在,即使需要填充额外的零,也始终保持最多2位小数。
任何帮助表示赞赏!
您的代码中有两件事可以改进。
首先,向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);
我使用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));
这对你有用:
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));
}
您正在将BigDecimal
转换回double
,它基本上修剪了尾随的零。
你可以返回BigDecimal
或BigDecimal.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();
}