2013-04-30 14 views
13

Sto provando a formattare alcuni numeri in un programma Java. I numeri saranno sia doppi che interi. Quando gestisco i duplicati, voglio mantenere solo due decimali, ma quando gestisco gli interi voglio che il programma li mantenga inalterato. In altre parole:Java: utilizzare DecimalFormat per formattare i doppi e gli interi ma mantenere interi senza separatore decimale

Doubles - Ingresso

14.0184849945 

Doubles - Uscita

14.01 

interi - Ingresso

13 

interi - Uscita

13 (not 13.00) 

Esiste un modo per implementarlo nella stessa istanza DecimalFormat? Il mio codice è il seguente, finora:

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

Perché deve essere lo stesso Istanza 'DecimalFormat'? Cosa c'è di sbagliato nell'avere 2 istanze di 'DecimalFormat', una per mantenere due cifre oltre il punto decimale e una per non avere cifre oltre il punto decimale? – rgettman

+0

Poiché i numeri che il programma formatta ogni volta sono doppi o interi, senza conoscere il tipo prima della formazione. Quindi, voglio la stessa istanza che "comprenderà" se un numero è doppio - per tagliare punti decimali extra - o è un numero intero - per mantenerlo inalterato. – Lefteris008

risposta

26

Si può solo impostare il minimumFractionDigits a 0. In questo modo:

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

Grazie, questo ha risolto il problema! :) – Lefteris008

+0

ora ha un formato da 44.0 a 44 e da 55.60 a 55.6. Come mantenere lo zero alla fine usando il formato? – user1510006

3

Potrebbe non solo Wrapper in una chiamata Utility. Per esempio

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); 
    } 
} 

È quindi possibile solo fare le cose come: MyFormatter.format(int) ecc

Problemi correlati