Converting a string to an integer on Android Converting a string to an integer on Android android android

Converting a string to an integer on Android


See the Integer class and the static parseInt() method:

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

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

You will need to catch NumberFormatException though in case of problems whilst parsing, so:

int myNum = 0;try {    myNum = Integer.parseInt(et.getText().toString());} catch(NumberFormatException nfe) {   System.out.println("Could not parse " + nfe);} 


int in = Integer.valueOf(et.getText().toString());//orint in2 = new Integer(et.getText().toString());


Use regular expression:

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

output:i=1234;

If you need first number combination then you should try below code:

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

output:i=123;