2013-05-08 83 views
1

我想把一个双精度数舍入到最接近的两个小数位,但是它只是四舍五入到最接近的整数。爪哇,四舍五入到小数点后两位数

例如,19634.0而不是19634.95。

这是当前的代码,我使用的舍入

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

我看不到我要去的地方错了。

非常感谢您的帮助。

+1

在相关处插入100.0d。并阅读铸造规则。 – 2013-05-08 13:32:32

+0

这是问题吗?施法规则说int会被upcast。 – 2013-05-08 13:33:15

+0

你有看看RoundingMode类吗?如果你使用BigDecimal则更容易 - http://docs.oracle.com/javase/6/docs/api/java/math/RoundingMode.html – manub 2013-05-08 13:34:37

回答

2

你是否真的想把值舍入到2个地方,这会导致代码中出现滚球错误,或者只显示2位小数?检出String.format()。复杂但非常强大。

2

您可以使用DecimalFormat对象:

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

System.out.println (df.format (19634.95)); 
1

你可能想看看DecimalFormat类。

double x = 4.654; 

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

这给出了“x = 4.65”。在模式#0之间的区别是,零始终显示,#不会,如果最后的是0

5

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

因此Math.round(Math.PI*Radius()*Radius()*100)/100将变成long19634)。

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

+0

哎呀,你是对的。节录。 – 2013-05-08 13:40:23

+1

除了@IvanKoblik指出的小错误外,这是正确解释问题中描述的问题的唯一答案。 – JeremyP 2013-05-08 13:43:41

+0

我修复了@IvanKoblik指出的错误。 – johnchen902 2013-05-08 13:45:41

0

以下示例来自this forum,但似乎是您要查找的内容。

double roundTwoDecimals(double d) { 
     DecimalFormat twoDForm = new DecimalFormat("#.##"); 
     return Double.valueOf(twoDForm.format(d)); 
} 
相关问题