2009-11-16 19 views
26

sto usando DecimalFormat in formato raddoppia a 2 cifre decimali come questo:zeri Visualizza imbottitura utilizzando DecimalFormat

DecimalFormat dec = new DecimalFormat("#.##"); 
double rawPercent = ((double)(count.getCount().intValue())/
          (double)(total.intValue())) * 100.00; 
double percentage = Double.valueOf(dec.format(rawPercent)); 

Funziona, ma se ho un numero come 20, mi dà questo:

20.0 

e voglio che questo:

20.00 

Qualche suggerimento?

risposta

31

La classe DecimalFormat serve per trasformare un valore numerico decimale in una stringa. Nel tuo esempio, stai prendendo la stringa che proviene dal metodo format() e la rimetti in una doppia variabile. Se stai emettendo quella doppia variabile, non vedresti la stringa formattata. Vedere l'esempio di codice qui sotto e la sua uscita:

int count = 10; 
int total = 20; 
DecimalFormat dec = new DecimalFormat("#.00"); 
double rawPercent = ((double)(count)/(double)(total)) * 100.00; 

double percentage = Double.valueOf(dec.format(rawPercent)); 

System.out.println("DF Version: " + dec.format(rawPercent)); 
System.out.println("double version: " + percentage); 

quali uscite:

"DF Version: 50.00" 
"double version: 50.0" 
+0

grazie - ha senso, e ora funziona perfettamente – mportiz08

7

Utilizzare il formato "# .00".

+0

che non funziona neanche – mportiz08

+0

non avete ci ha mostrato la sua dichiarazione di stampa. Se dec.format (percentuale), il formato funzionerà. –

+0

È preferibile utilizzare "0.00" poiché "# .00" formerebbe 0 come .00 che a mio parere non sembra buono. – ka3ak

0

Provare a utilizzare invece un formato decimale di "0,00". Secondo lo JavaDocs, questo non eliminerà gli 0 in eccesso.

+0

sta ancora eliminando uno zero in più con il formato "0.00" :( – mportiz08

5

si può provare qualcosa di simile:

DecimalFormat df = new DecimalFormat("0.000000"); 
df.setMinimumFractionDigits(0); 
df.setMinimumIntegerDigits(2); 

In questo modo è possibile garantire il numero minimo di cifre prima o dopo il decimale

+0

Questo non funziona –

+0

'df.setMinimumFractionDigits (2);' ha funzionato per me. –

2

Prova questo codice:

int count = 10; 
int total = 20; 
int another=0; 
DecimalFormat df = new DecimalFormat("0.00"); 

System.out.println(df.format(count)); 
System.out.println(df.format(total)); 
System.out.println(df.format(another)); 

L'output è: 10,00 20,00 0,00

13

provare questo codice:

BigDecimal decimal = new BigDecimal("100.25"); 

BigDecimal decimal2 = new BigDecimal("1000.70"); 

BigDecimal decimal3 = new BigDecimal("10000.00"); 

DecimalFormat format = new DecimalFormat("###,###,###,###,###.##"); 

format.setDecimalSeparatorAlwaysShown(true); 

format.setMinimumFractionDigits(2); 

System.out.println(format.format(decimal)); 

System.out.println(format.format(decimal2)); 

System.out.println(format.format(decimal3)); 

Risultato:

100.25 

1,000.70 

10,000.00 
+0

In che modo la tua risposta aggiunge qualcosa alla domanda? La domanda è stata risolta 4 anni fa e apparentemente con la soddisfazione dell'OP. Inoltre: ti preghiamo di utilizzare le strutture di formattazione fornite per formattare il tuo codice. –

+0

questa è la risposta giusta – MobileMon

+0

Questa risposta mi ha aiutato, dato che ho usato 'format.setMinimumFractionDigits()'. Sebbene non fosse lo stesso del caso dell'OP, nel mio caso avevo bisogno di cambiare il numero di cifre decimali in base ad altri fattori, quindi questo mi ha permesso di mantenere un unico schema generale, ma variare il numero di posizioni decimali. – Fodder

2

ho trovato il mio piccolo programma di test utile e vogliono condividerlo con te Godere.

package be.softwarelab.numbers; 

import java.text.DecimalFormat; 
import java.text.DecimalFormatSymbols; 
import java.util.Locale; 

public class DecimalNumbers { 

    private static final double ZERO = 0; 
    private static final double TEN = 10.0; 
    private static final double PI = Math.PI;       // 3.141592653589793; 
    private static final double MILLIONS = Math.E * Math.pow(10, 6); // 2718281.828459045; 
    private static final double NINERS = 9999999.99999; 

    public static void main(String[] args) { 

     String format01 = "#.#"; 
     String format02 = "0.#"; 
     String format03 = "#.0"; 
     String format04 = "0.0"; 
     String format05 = "##.#"; 
     String format06 = "00.#"; 

     String formatAll = "###,###.###"; 
     String formatLong = "#.#########"; 

     System.out.println("====== ZERO ================================================="); 
     showResult(ZERO, format01, Locale.US); 
     showResult(ZERO, format02, Locale.US); 
     showResult(ZERO, format03, Locale.US); 
     showResult(ZERO, format04, Locale.US); 
     showResult(ZERO, format05, Locale.US); 
     showResult(ZERO, format06, Locale.US); 
     System.out.println("====== TEN ================================================="); 
     showResult(TEN, format01, Locale.US); 
     showResult(TEN, format02, Locale.US); 
     showResult(TEN, format03, Locale.US); 
     showResult(TEN, format04, Locale.US); 
     showResult(TEN, format05, Locale.US); 
     showResult(TEN, format06, Locale.US); 
     System.out.println("====== PI ================================================="); 
     showResult(PI, format01, Locale.US); 
     showResult(PI, format02, Locale.US); 
     showResult(PI, format03, Locale.US); 
     showResult(PI, format04, Locale.US); 
     showResult(PI, format05, Locale.US); 
     showResult(PI, format06, Locale.US); 
     System.out.println("====== MILLIONS ============================================="); 
     showResult(MILLIONS, formatAll, Locale.US); 
     showResult(MILLIONS, formatAll, Locale.GERMANY); 
     showResult(MILLIONS, formatAll, Locale.FRANCE); 
     showResult(MILLIONS, formatAll, new Locale("nl", "BE")); 
     System.out.println("====== NINERS ============================================="); 
     showResult(NINERS, format01, Locale.US); 
     showResult(NINERS, format02, Locale.US); 
     showResult(NINERS, format03, Locale.US); 
     showResult(NINERS, format04, Locale.US); 
     showResult(NINERS, format05, Locale.US); 
     showResult(NINERS, format06, Locale.US); 
     showResult(NINERS, formatLong, Locale.US); 
     System.out.println("============================================================="); 
    } 

    public static void showResult(double number, String format, Locale locale) { 
     // Using a Locale to see the differences between regions. 
     DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(locale); 
     DecimalFormat formatter = new DecimalFormat (format, otherSymbols); 

     // Create the String result 
     String output = formatter.format(number); 

     // Format the output for a nice presentation. 
     System.out.format(" %s %20s %11s = %20s\n", locale, number, format, output); 
    } 
} 

Questo si traduce in:

====== ZERO ================================================= 
en_US     0.0   #.# =     0 
en_US     0.0   0.# =     0 
en_US     0.0   #.0 =     .0 
en_US     0.0   0.0 =     0.0 
en_US     0.0  ##.# =     0 
en_US     0.0  00.# =     00 
====== TEN ================================================= 
en_US     10.0   #.# =     10 
en_US     10.0   0.# =     10 
en_US     10.0   #.0 =     10.0 
en_US     10.0   0.0 =     10.0 
en_US     10.0  ##.# =     10 
en_US     10.0  00.# =     10 
====== PI ================================================= 
en_US 3.141592653589793   #.# =     3.1 
en_US 3.141592653589793   0.# =     3.1 
en_US 3.141592653589793   #.0 =     3.1 
en_US 3.141592653589793   0.0 =     3.1 
en_US 3.141592653589793  ##.# =     3.1 
en_US 3.141592653589793  00.# =     03.1 
====== MILLIONS ============================================= 
en_US 2718281.828459045 ###,###.### =  2,718,281.828 
de_DE 2718281.828459045 ###,###.### =  2.718.281,828 
fr_FR 2718281.828459045 ###,###.### =  2 718 281,828 
nl_BE 2718281.828459045 ###,###.### =  2.718.281,828 
====== NINERS ============================================= 
en_US  9999999.99999   #.# =    10000000 
en_US  9999999.99999   0.# =    10000000 
en_US  9999999.99999   #.0 =   10000000.0 
en_US  9999999.99999   0.0 =   10000000.0 
en_US  9999999.99999  ##.# =    10000000 
en_US  9999999.99999  00.# =    10000000 
en_US  9999999.99999 #.######### =  9999999.99999 
============================================================= 
Problemi correlati