2017-05-22 99 views
-1

我試圖用一個簡單的十進制格式化,但得到意想不到的結果: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

+0

61.03和4.59似乎是正確的我 –

+3

'61.03應該是61.04'都能跟得上它不應該,'61.034'舍入到'61.03'無論你是否將'HALF_UP'四捨五入。您可能正在尋找'CEILING',其中值將被封裝爲下一個整數而不是四捨五入。 – Aaron

+0

由於您正在嘗試將61.034999舍入到61.04,因此您似乎希望在最大值時得到2個小數位。因此,你可以嘗試圍繞你的輸入+ 0.001,即61.034999 + 0.001 = 61.035999,然後應該是半高達61.04 – Thomas

回答

0

61.034將總是四捨五入爲61.03,因爲舍入帶來了最接近的整數。

HALF_UP/HALF_DOWN僅衝擊值是在兩個整數之間的界限,即3.5將被舍入到4HALF_UP而是3HALF_DOWN

你似乎在尋找的不是一個舍入函數,而是上限函數,其中值將被帶到最近的上述整數:61.03461.043.54

便利中,RoundingMode枚舉提供了這樣的功能,DecimalFormatRoundingMode.CEILING領域:

DecimalFormat m_numberFormat2DP1 = new DecimalFormat("0.00"); 
m_numberFormat2DP1.setRoundingMode(RoundingMode.CEILING); 
System.out.println(m_numberFormat2DP1.getRoundingMode()); 
System.out.println(m_numberFormat2DP1.format(amt));//result is 61.04 
System.out.println(m_numberFormat2DP1.format(amt1));//result is 4.59 

你可以看到它在行動here

0
public class DecimalFormatDemo { 
public static void main(String args[]) { 
DecimalFormat df1 = new DecimalFormat("###,###.0000"); 
System.out.println(df1.format(111111123456.12)); 

Locale.setDefault(Locale.US); 
DecimalFormat df2= new DecimalFormat("###,###.0000"); 
System.out.println(df2.format(111111123456.12)); 

DecimalFormat df3= new DecimalFormat(); 
myformat3.applyPattern("##,###.000"); 
System.out.println(df3.format(11112345.12345)); 




    DecimalFormat df4= new DecimalFormat(); 
    myformat4.applyPattern("0.000E0000"); 
    System.out.println(df4.format(10000)); 
    System.out.println(df4.format(12345678.345)); 


    DecimalFormat df5= null; 
    try{ 
    df5= (DecimalFormat)NumberFormat.getPercentInstance(); 
}catch(ClassCastException e){ 
    <span style="white-space:pre"> </span> System.err.println(e); 
} 
df5.applyPattern("00.0000%"); 
System.out.println(df5.format(0.34567)); 
System.out.println(df5.format(1.34567));   

}
} 我希望我可以幫你