我試圖用一個簡單的十進制格式化,但得到意想不到的結果:JAVA DecimalFormat的四捨五入問題
float amt = 61.0349998474121F;
float amt1 = 4.5850000381470F;
DecimalFormat m_numberFormat2DP = new DecimalFormat("0.000");
System.out.println(m_numberFormat2DP.getRoundingMode());
System.out.println(m_numberFormat2DP.format(amt));
System.out.println(m_numberFormat2DP.format(amt1));
DecimalFormat m_numberFormat2DP1 = new DecimalFormat("0.00");
//m_numberFormat2DP1.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(m_numberFormat2DP1.getRoundingMode());
System.out.println(m_numberFormat2DP1.format(amt));//result should be 61.04
System.out.println(m_numberFormat2DP1.format(amt1));//result should be 4.59
這是我的代碼試圖HALF_UP很好,但結果是相同的,我接受了最後的SOP輸出是61.03和4.59。 61.03應該是61.04
61.03和4.59似乎是正確的我 –
'61.03應該是61.04'都能跟得上它不應該,'61.034'舍入到'61.03'無論你是否將'HALF_UP'四捨五入。您可能正在尋找'CEILING',其中值將被封裝爲下一個整數而不是四捨五入。 – Aaron
由於您正在嘗試將61.034999舍入到61.04,因此您似乎希望在最大值時得到2個小數位。因此,你可以嘗試圍繞你的輸入+ 0.001,即61.034999 + 0.001 = 61.035999,然後應該是半高達61.04 – Thomas