2009-11-16 14 views
26

estoy usando DecimalFormat a formato duplica a 2 decimales como este:ceros Mostrar relleno utilizando DecimalFormat

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

Funciona, pero si tengo un número como 20, me da esto:

20.0 

y quiero que esto:

20.00 

¿Alguna sugerencia?

Respuesta

31

La clase DecimalFormat es para transformar un valor numérico decimal en una cadena. En su ejemplo, está tomando el String que proviene del método format() y lo coloca de nuevo en una variable doble. Si está generando esa doble variable, no verá la cadena formateada. Vea el ejemplo de código siguiente y su salida:

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

que da salida:

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

gracias - eso tiene sentido, y ahora está funcionando perfectamente – mportiz08

7

Utilice el formato "# .00".

+0

que no funciona bien – mportiz08

+0

No ha nos mostró su estado de impresión. Si lo hace dec.format (porcentaje), el formato funcionará. –

+0

Es mejor usar "0.00" ya que "# .00" formatearía 0 como .00 que no se ve bien en mi opinión. – ka3ak

0

Pruebe usar un DecimalFormat de "0.00" en su lugar. De acuerdo con JavaDocs, esto no eliminará los 0 adicionales.

+0

todavía está quitando un cero adicional con el formato "0.00" :( – mportiz08

5

Usted puede intentar algo como:

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

esta manera se puede garantizar que el número mínimo de dígitos antes o después del decimal

+0

Esto no funciona. –

+0

'df.setMinimumFractionDigits (2);' funcionó para mí. –

2

Pruebe este código:

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

La salida es: 10,00 20,00 0,00

13

probar este código:

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

Resultado:

100.25 

1,000.70 

10,000.00 
+0

¿Cómo su respuesta agrega algo a la pregunta? La pregunta ha sido respondida hace 4 años y aparentemente a satisfacción del OP. También: utilice las herramientas de formato provistas para formatear su código. –

+0

esta es la respuesta correcta – MobileMon

+0

Esta respuesta me ayudó, ya que utilicé 'format.setMinimumFractionDigits()'. Si bien no es lo mismo que el caso del OP, en mi caso, tuve que cambiar el número de decimales en función de otros factores, por lo que esto me permitió mantener un único patrón general, pero variar el número de decimales. – Fodder

2

he encontrado mi pequeño programa de prueba útil y quieren compártelo con usted Disfrutar.

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

Esto se traduce en:

====== 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 
============================================================= 
Cuestiones relacionadas