我想把一個雙精度數舍入到最接近的兩個小數位,但是它只是四捨五入到最接近的整數。爪哇,四捨五入到小數點後兩位數
例如,19634.0而不是19634.95。
這是當前的代碼,我使用的舍入
double area = Math.round(Math.PI*Radius()*Radius()*100)/100;
我看不到我要去的地方錯了。
非常感謝您的幫助。
我想把一個雙精度數舍入到最接近的兩個小數位,但是它只是四捨五入到最接近的整數。爪哇,四捨五入到小數點後兩位數
例如,19634.0而不是19634.95。
這是當前的代碼,我使用的舍入
double area = Math.round(Math.PI*Radius()*Radius()*100)/100;
我看不到我要去的地方錯了。
非常感謝您的幫助。
你是否真的想把值舍入到2個地方,這會導致代碼中出現滾球錯誤,或者只顯示2位小數?檢出String.format()
。複雜但非常強大。
您可以使用DecimalFormat
對象:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);
System.out.println (df.format (19634.95));
你可能想看看DecimalFormat
類。
double x = 4.654;
DecimalFormat twoDigitFormat = new DecimalFormat("#.00");
System.out.println("x=" + twoDigitFormat.format());
這給出了「x = 4.65」。在模式#
和0
之間的區別是,零始終顯示,#不會,如果最後的是0
好,Math.round(Math.PI*Radius()*Radius()*100)
是long
。 100
是int
。
因此Math.round(Math.PI*Radius()*Radius()*100)/100
將變成long
(19634
)。
將其更改爲Math.round(Math.PI*Radius()*Radius()*100)/100.0
。 100.0
是double
,結果也將是double
(19634.95
)。
哎呀,你是對的。節錄。 – 2013-05-08 13:40:23
除了@IvanKoblik指出的小錯誤外,這是正確解釋問題中描述的問題的唯一答案。 – JeremyP 2013-05-08 13:43:41
我修復了@IvanKoblik指出的錯誤。 – johnchen902 2013-05-08 13:45:41
以下示例來自this forum,但似乎是您要查找的內容。
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
在相關處插入100.0d。並閱讀鑄造規則。 – 2013-05-08 13:32:32
這是問題嗎?施法規則說int會被upcast。 – 2013-05-08 13:33:15
你有看看RoundingMode類嗎?如果你使用BigDecimal則更容易 - http://docs.oracle.com/javase/6/docs/api/java/math/RoundingMode.html – manub 2013-05-08 13:34:37