Java-Convertir entero a cadena [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Dado un número:

int number = 1234;

Que sería la" mejor " manera de convertir esto a una cadena:

String stringNumber = "1234";

He intentado buscar (googlear) una respuesta pero no muchos parecían "confiables".

Author: Anderson Green, 2011-02-21

7 answers

Hay múltiples maneras:

  • String.valueOf(number) (mi preferencia)
  • "" + number (No se como lo maneja el compilador, quizás es tan eficiente como el anterior)
  • Integer.toString(number)
 714
Author: Bozho,
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-02-21 21:12:30

La clase Integer tiene el método estático toString () - puede usarlo:

int i = 1234;
String str = Integer.toString(i);

Devuelve un objeto String que representa el entero especificado. El argumento se convierte en una representación decimal firmada y se devuelve como una cadena, exactamente como si el argumento y la base 10 fueran dados como argumentos al método toString(int, int).

 48
Author: smas,
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-02-21 20:51:24

Utilice siempre String.valueOf(number) o Integer.toString(number).

Usar "" + número es una sobrecarga y hace lo siguiente:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();
 34
Author: AllThatICode,
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
2015-08-21 07:17:02

Esto servirá. Bastante confiable. : )

    ""+number;

Solo para aclarar, esto funciona y es aceptable de usar a menos que esté buscando una micro optimización.

 33
Author: Nishant,
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-01-24 09:07:02

La forma en que sé cómo convertir un entero en una cadena es usando el siguiente código:

Integer.toString(int);

Y

String.valueOf(int);

Si tuvieras un entero i, y una cadena s, entonces se aplicaría lo siguiente:

int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);

Si desea convertir una cadena " s "en un entero "i", entonces lo siguiente funcionaría:

i = Integer.valueOf(s).intValue();
 16
Author: danjonila,
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-26 08:46:08

Este es el método que usé para convertir el entero a cadena.Corrígeme si hice mal.

/**
 * @param a
 * @return
 */
private String convertToString(int a) {

    int c;
    char m;
    StringBuilder ans = new StringBuilder();
    // convert the String to int
    while (a > 0) {
        c = a % 10;
        a = a / 10;
        m = (char) ('0' + c);
        ans.append(m);
    }
    return ans.reverse().toString();
}
 2
Author: Jegan,
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-10-28 04:40:41

Uno que uso a menudo:

 Integer.parseInt("1234");

El punto es que hay muchas maneras de hacer esto, todas igualmente válidas. En cuanto a cuál es el más óptimo / eficiente, tendrías que preguntar a alguien más.

 -3
Author: DYezek,
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-07-10 21:20:08