¿Cómo puedo rellenar un entero con ceros a la izquierda?


¿Cómo se deja un int con ceros al convertir a un String en java?

Básicamente estoy buscando rellenar enteros hasta 9999 con ceros a la izquierda (por ejemplo, 1 = 0001).

Author: James Wong, 2009-01-23

13 answers

Uso java.lang.String.format(String,Object...) así:

String.format("%05d", yournumber);

Para relleno cero con una longitud de 5. Para la salida hexadecimal, sustitúyase d por x como en "%05x".

Las opciones de formato completo se documentan como parte de java.util.Formatter.

 1480
Author: Yoni Roit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 19:17:43

Si por alguna razón utiliza Java pre 1.5, puede probar con el método Lang de Apache Commons

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
 98
Author: Boris Pavlović,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-31 21:33:43

Digamos que quieres imprimir 11 como 011

Podrías usar un formateador: "%03d".

introduzca la descripción de la imagen aquí

Puedes usar este formateador así:

int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);

Alternativamente, algunos métodos java soportan directamente estos formateadores:

System.out.printf("%03d", a);
 68
Author: bvdb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-07 05:24:04

Encontró este ejemplo... Probaremos...

import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}

Probado esto y:

String.format("%05d",number);

Ambos funcionan, para mis propósitos creo que String.El formato es mejor y más sucinto.

 26
Author: Omar Kooheji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-10 17:44:32

Si el rendimiento es importante en su caso, podría hacerlo usted mismo con menos sobrecarga en comparación con la función String.format:

/**
 * @param in The integer value
 * @param fill The number of digits to fill
 * @return The given value left padded with the given number of digits
 */
public static String lPadZero(int in, int fill){

    boolean negative = false;
    int value, len = 0;

    if(in >= 0){
        value = in;
    } else {
        negative = true;
        value = - in;
        in = - in;
        len ++;
    }

    if(value == 0){
        len = 1;
    } else{         
        for(; value != 0; len ++){
            value /= 10;
        }
    }

    StringBuilder sb = new StringBuilder();

    if(negative){
        sb.append('-');
    }

    for(int i = fill; i > len; i--){
        sb.append('0');
    }

    sb.append(in);

    return sb.toString();       
}

Rendimiento

public static void main(String[] args) {
    Random rdm;
    long start; 

    // Using own function
    rdm = new Random(0);
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        lPadZero(rdm.nextInt(20000) - 10000, 4);
    }
    System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");

    // Using String.format
    rdm = new Random(0);        
    start = System.nanoTime();

    for(int i = 10000000; i != 0; i--){
        String.format("%04d", rdm.nextInt(20000) - 10000);
    }
    System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}

Resultado

Función propia: 1697ms

Cuerda.formato: 38134ms

 15
Author: das Keks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-03 15:05:12

Puedes usar Google Guayaba :

Maven:

<dependency>
     <artifactId>guava</artifactId>
     <groupId>com.google.guava</groupId>
     <version>14.0.1</version>
</dependency>

Código de ejemplo:

String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"

Nota:

Guava es biblioteca muy útil, también proporciona un montón de características que se relacionan con Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

Ref: GuavaExplained

 14
Author: ThoQ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 16:26:48

Aunque muchos de los enfoques anteriores son buenos, pero a veces necesitamos formatear enteros, así como flotadores. Podemos usar esto, particularmente cuando necesitamos rellenar un número particular de ceros a la izquierda y a la derecha de los números decimales.

import java.text.NumberFormat;  
public class NumberFormatMain {  

public static void main(String[] args) {  
    int intNumber = 25;  
    float floatNumber = 25.546f;  
    NumberFormat format=NumberFormat.getInstance();  
    format.setMaximumIntegerDigits(6);  
    format.setMaximumFractionDigits(6);  
    format.setMinimumFractionDigits(6);  
    format.setMinimumIntegerDigits(6);  

    System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));  
    System.out.println("Formatted Float   : "+format.format(floatNumber).replace(",",""));  
 }    
}  
 2
Author: Deepak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-02 19:13:07
int x = 1;
System.out.format("%05d",x);

Si desea imprimir el texto formateado directamente en la pantalla.

 2
Author: Shashi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-24 13:29:48

Prueba este:

DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9);   // 0009
String a = df.format(99);  // 0099
String b = df.format(999); // 0999
 2
Author: Brijesh Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-25 14:26:15

Compruebe mi código que funcionará para integer y String.

Supongamos que nuestro primer número es 2. Y queremos agregar ceros a eso para que la longitud de la cadena final sea 4. Para ello puede utilizar el siguiente código

    int number=2;
    int requiredLengthAfterPadding=4;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);
 0
Author: Fathah Rehman P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-24 10:29:17

Necesita usar un formateador, el siguiente código usa NumberFormat

    int inputNo = 1;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumIntegerDigits(4);
    nf.setMinimumIntegerDigits(4);
    nf.setGroupingUsed(false);

    System.out.println("Formatted Integer : " + nf.format(inputNo));

Salida: 0001

 0
Author: Jobin Joseph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-08 10:30:50
public static String zeroPad(long number, int width) {
   long wrapAt = (long)Math.pow(10, width);
   return String.valueOf(number % wrapAt + wrapAt).substring(1);
}

El único problema con este enfoque es que te hace ponerte el sombrero de pensar para averiguar cómo funciona.

 -2
Author: johncurrier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-05 19:36:56

No se necesitan paquetes:

String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;

Esto rellenará la cadena a tres caracteres, y es fácil agregar una parte más para cuatro o cinco. Sé que esta no es la solución perfecta de ninguna manera (especialmente si quieres una cuerda acolchada grande), pero me gusta.

 -5
Author: NoShadowKick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-09 12:52:48