Converting a string to an integer on Android

629,956

Solution 1

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);
} 

Solution 2

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

Solution 3

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;

Solution 4

Use regular expression:

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

output:

i=123;
j=123;
k=123;

Solution 5

Use regular expression is best way to doing this as already mentioned by ashish sahu

public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
Share:
629,956

Related videos on Youtube

James Andrew
Author by

James Andrew

Updated on April 20, 2022

Comments

  • James Andrew
    James Andrew about 2 years

    How do I convert a string into an integer?

    I have a textbox I have the user enter a number into:

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

    And the value is assigned to the string hello.

    I want to convert it to a integer so I can get the number they typed; it will be used later on in code.

    Is there a way to get the EditText to a integer? That would skip the middle man. If not, string to integer will be just fine.

  • Gabriel Fair
    Gabriel Fair over 12 years
    What about using manuel's way below? Is it more secure to use parseInt over valueOf?
  • Patrick M
    Patrick M over 9 years
    That's an awful lot of code for one line (just my preference).
  • Brett Moan
    Brett Moan over 9 years
    Aye, I wouldnt do it that way either, it was more a reference to the OP's "skip the middle man" comment.
  • Ahamadullah Saikat
    Ahamadullah Saikat over 6 years
    exactly what I was looking for.
  • U. Windl
    U. Windl about 5 years
    Mark your code parts as code; that will make the answer more readable!