2013-04-30 107 views
13

我試圖在Java程序中格式化一些數字。數字將是雙打和整數。處理雙精度時,我只想保留兩位小數點,但是在處理整數時我希望程序不會受到影響。換句話說:Java:使用DecimalFormat格式化雙精度和整數,但保留不包含小數點分隔符的整數

雙打 - 輸入

14.0184849945 

雙打 - 輸出

14.01 

整數 - 輸入

13 

整數 - 輸出

13 (not 13.00) 

有沒有一種方法可以在中實現這個 DecimalFormat實例?我的代碼如下,目前爲止:

DecimalFormat df = new DecimalFormat("#,###,##0.00"); 
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH); 
otherSymbols.setDecimalSeparator('.'); 
otherSymbols.setGroupingSeparator(','); 
df.setDecimalFormatSymbols(otherSymbols); 
+4

爲什麼一定是相同的'DecimalFormat'實例?有2個'DecimalFormat'實例有什麼問題,一個保留兩位數字越過小數點,一個沒有任何數字越過小數點? – rgettman 2013-04-30 21:29:00

+0

因爲每次編程格式的數字都是雙精度或整數,而不知道形成之前的類型。所以,我想要一個能夠「理解」數字是否是雙精度的修正小數點的實例 - 或者它是一個整數 - 以保持不受影響。 – Lefteris008 2013-05-01 09:50:19

回答

26

您可以只設置minimumFractionDigits爲0。像這樣:

public class Test { 

    public static void main(String[] args) { 
     System.out.println(format(14.0184849945)); // prints '14.01' 
     System.out.println(format(13)); // prints '13' 
     System.out.println(format(3.5)); // prints '3.5' 
     System.out.println(format(3.138136)); // prints '3.13' 
    } 

    public static String format(Number n) { 
     NumberFormat format = DecimalFormat.getInstance(); 
     format.setRoundingMode(RoundingMode.FLOOR); 
     format.setMinimumFractionDigits(0); 
     format.setMaximumFractionDigits(2); 
     return format.format(n); 
    } 

} 
+0

謝謝,解決了這個問題! :) – Lefteris008 2013-05-01 10:43:23

+0

現在格式爲44.0到44和55.60到55.6。 如何保持使用格式的最後零? – user1510006 2016-09-27 10:00:59

3

你能不能把這個封裝到一個實用程序調用中。例如

public class MyFormatter { 

    private static DecimalFormat df; 
    static { 
    df = new DecimalFormat("#,###,##0.00"); 
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH); 
    otherSymbols.setDecimalSeparator('.'); 
    otherSymbols.setGroupingSeparator(','); 
    df.setDecimalFormatSymbols(otherSymbols); 
    } 

    public static <T extends Number> String format(T number) { 
    if (Integer.isAssignableFrom(number.getClass()) 
     return number.toString(); 

    return df.format(number); 
    } 
} 

然後你可以只是做這樣的事情:MyFormatter.format(int)

相關問題