1

我正在尝试将双精度数四舍五入到最接近的两位小数,但是,它只是四舍五入到最接近的整数。

例如,19634.0 而不是 19634.95。

这是我用于舍入的当前代码

double area = Math.round(Math.PI*Radius()*Radius()*100)/100;

我看不出我哪里出错了。

非常感谢您的帮助。

4

5 回答 5

5

嗯,Math.round(Math.PI*Radius()*Radius()*100)long100int

所以Math.round(Math.PI*Radius()*Radius()*100) / 100会变成long( 19634)。

将其更改为Math.round(Math.PI*Radius()*Radius()*100) / 100.0. 100.0double,结果也将是double( 19634.95)。

于 2013-05-08T13:35:11.010 回答
2

您可以使用一个DecimalFormat对象:

DecimalFormat df = new DecimalFormat ();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);

System.out.println (df.format (19634.95));
于 2013-05-08T13:34:23.227 回答
2

您是否真的想要将值四舍五入到 2 位,这会导致代码中出现滚雪球式舍入错误,或者只是显示带有 2 个小数位的数字?退房String.format()。复杂但非常强大。

于 2013-05-08T13:31:24.613 回答
1

你可能想看看这个DecimalFormat类。

double x = 4.654;

DecimalFormat twoDigitFormat = new DecimalFormat("#.00");
System.out.println("x=" + twoDigitFormat.format());

这给出“x = 4.65”。模式之间的区别在于#0总是显示零,如果最后一个是 0,# 则不会。

于 2013-05-08T13:34:29.930 回答
0

以下示例来自此论坛,但似乎是您正在寻找的。

 double roundTwoDecimals(double d) {
      DecimalFormat twoDForm = new DecimalFormat("#.##");
      return Double.valueOf(twoDForm.format(d));
 }
于 2013-05-08T13:35:55.693 回答