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.
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);
}
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());
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;
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;
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]", ""));
}
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);
}
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);
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);
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
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
- agarra la vista usando
findViewById(R.id.button1)
- use
((Button)______)
para lanzar elView
como unButton
- Llame a
.GetText()
para obtener la entrada de texto del Botón - Llama a
.toString()
para convertir el Carácter Que Varía en una cadena - Llame a
.ReplaceAll()
con"[\\D]"
para reemplazar todos los Caracteres que no sean Dígitos con "" (nada) - Llama a
Integer.parseInt()
grab y devuelve un entero de la cadena de solo dígitos.
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);
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