2013-01-10 164 views
6

我正在嘗試類NumberFormat的方法和功能,我已經達到了一個奇怪的結果。我編譯和運行下面的程序:NumberFormat setMaximumFractionDigits方法

public static void main(String[] args) { 

Locale loc = Locale.US; 
    NumberFormat nf = NumberFormat.getInstance(loc); 
    System.out.println("Max: "+nf.getMaximumFractionDigits()); 
    System.out.println("Min: "+nf.getMinimumFractionDigits()); 
    try { 
     Number d = nf.parse("4527.9997539"); 
     System.out.println(d); 
     // nf.setMaximumFractionDigits(4); 
     System.out.println(nf.format(4527.999753)); 
    } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

輸出是:

Max: 3 
Min: 0 
4527.9997539 
4,528 

這意味着,它沒有考慮任何分數數字。如果我取消註釋:

nf.setMaximumFractionDigits(4); 

輸出爲:

Max: 3 
Min: 0 
4527.9997539 
4,527.9998 

換句話說,它的工作原理確定。在方法setMaximumFractionDigits()中實際發生了什麼,並且它在第一種情況下不會帶有包含3個小數位的數字?

+0

你的意思是手動設置數字的小數位嗎? –

回答

11

我終於找到了答案。方法setMaximumFractionDigits()只對方法format()有效。它與parse()無關。在我的代碼片段中,我使用方法format()手動設置小數位數爲4,因此它會影響結果。

1

從解析的字符串創建的數字有更多的小數位數。但是,當您嘗試輸出格式爲MaximumFractionDigits以從任何給定數字創建字符串時。

+0

我還不能理解問題的原因。即使我將最大數字手動(通過方法setMaximumFractionDigits)設置爲3,它也會返回一個沒有小數部分的數字。我認爲它應該有一個3位數的小數部分。 – arjacsoh

2

如果你想手動小數的個數使用下列選項來設置:

首先:

//sets 'd' to 3 decimal places & then assigns it to 'formattedNum' 
    String formattedNum = String.format("%.3f", d); //variable 'd' taken from your code above 

OR

//declares an object of 'DecimalFormat' 
    DecimalFormat aDF = new DecimalFormat("#.000"); 

    //formats value stored in 'd' to three decimal places 
    String fomrattedNumber = aDF.format(d); 

在我看來,第二個選項套裝最適合你的情況。