Convertir una cadena a un entero en Android


¿Cómo convertir una cadena en un entero?

Tengo un cuadro de texto En el que el usuario introduce un número:

EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();

Y el valor se asigna a la cadena hello.

Quiero convertirlo a un entero para que pueda obtener el número que escribieron; se utilizará más adelante en el código.

¿Hay una manera de obtener el EditText a un entero? Eso evitaría al intermediario. Si no, string a integer estará bien.

Author: HpTerm, 2010-04-25

11 answers

Vea la clase Integer y el método estático parseInt():

Http://developer.android.com/reference/java/lang/Integer.html

Integer.parseInt(et.getText().toString());

Usted tendrá que coger NumberFormatException aunque en caso de problemas durante el análisis, por lo que:

int myNum = 0;

try {
    myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
   System.out.println("Could not parse " + nfe);
} 
 376
Author: Jon,
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-05 14:55:57
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
 39
Author: manuel,
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-03-31 17:27:44

Usar expresión regular:

String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""));

Salida: i = 1234;

Si necesita la primera combinación de números, debe probar el siguiente código:

String s="abc123xyz456";
int i=NumberFormat.getInstance().parse(s).intValue();

Salida: i = 123;

 22
Author: Ashish Sahu,
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-10-02 17:22:43

Usar expresión regular:

int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));

Salida:

i=123;
j=123;
k=123;
 10
Author: Ashish Sahu,
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-01-31 19:41:18

Usar expresiones regulares es la mejor manera de hacer esto como ya lo mencionó ashish sahu

public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
 8
Author: ,
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-03-02 03:11:08

Pruebe este código que realmente está funcionando.

int number = 0;
try {
    number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
   System.out.println("parse value is not valid : " + e);
} 
 7
Author: Ravi Makvana,
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-02-20 08:11:39

Debes encubrir la cadena para que flote. Está funcionando.

float result = 0;
 if (TextUtils.isEmpty(et.getText().toString()) {
  return;
}

result = Float.parseFloat(et.getText().toString());

tv.setText(result); 
 4
Author: Tren Narek,
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-17 06:30:54

La mejor manera de convertir tu cadena en int es:

 EditText et = (EditText) findViewById(R.id.entry1);
 String hello = et.getText().toString();
 int converted=Integer.parseInt(hello);
 4
Author: Ravi Rupareliya,
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-01-10 08:56:11

Puede usar lo siguiente para analizar una cadena a un entero:

Valor Int = Entero.parseInt (TextView.getText().toString());

(1) entrada: 12 funcionará.. porque textview ha tomado este número 12 como cadena "12".

(2) input: "abdul" entonces lanzará una excepción que es NumberFormatException. Así que para resolver esto tenemos que utilizar try catch como he mencionado a continuación:

  int tax_amount=20;
  EditText edit=(EditText)findViewById(R.id.editText1);
     try
       {

        int value=Integer.parseInt(edit.getText().toString());
        value=value+tax_amount;
        edit.setText(String.valueOf(value));// to convert integer to string 

       }catch(NumberFormatException ee){
       Log.e(ee.toString());
       }

Es posible que también desee hacer referencia a la siguiente enlace para más información: http://developer.android.com/reference/java/lang/Integer.html

 4
Author: Abdul Rizwan,
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-09-02 09:30:48

También puedes hacerlo una línea:

int hello = Integer.parseInt(((Button)findViewById(R.id.button1)).getText().toString().replaceAll("[\\D]", ""));

Lectura de la orden de ejecución

  1. agarra la vista usando findViewById(R.id.button1)
  2. use ((Button)______) para lanzar el View como un Button
  3. Llame a .GetText() para obtener la entrada de texto del Botón
  4. Llama a .toString() para convertir el Carácter Que Varía en una cadena
  5. Llame a .ReplaceAll() con "[\\D]" para reemplazar todos los Caracteres que no sean Dígitos con "" (nada)
  6. Llama a Integer.parseInt() grab y devuelve un entero de la cadena de solo dígitos.
 2
Author: Brett Moan,
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-10-28 05:57:08

El método mucho más simple es usar el método decode de Integer así por ejemplo:

int helloInt = Integer.decode(hello);
 2
Author: Joseph Chotard,
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-02-09 16:26:45