[java] Converting a string to an integer on Android

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.

This question is related to java android string integer android-edittext

The answer is


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

There are five ways to convert The First Way :

String str = " 123" ;
int i = Integer.parse(str); 
output : 123

The second way :

String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123

The Third Way :

String str"123";
int i = new Integer(str);
output "123 

The Fourth Way :

String str"123";
int i = Integer.valueOf(Str);
output "123 

The Fifth Way :

String str"123";
int i = Integer.decode(str);
output "123 

There could be other ways But that's what I remember now


Kotlin

There are available Extension methods to parse them into other primitive types.

Java

String num = "10";
Integer.parseInt(num );

You can use the following to parse a string to an integer:

int value=Integer.parseInt(textView.getText().toString());

(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.

(2) input: "abdul" then it will throw an exception that is NumberFormatException. So to solve this we need to use try catch as I have mention below:

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

You may also want to refer to the following link for more information: http://developer.android.com/reference/java/lang/Integer.html


Best way to convert your string into int is :

 EditText et = (EditText) findViewById(R.id.entry1);
 String hello = et.getText().toString();
 int converted=Integer.parseInt(hello);

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]", ""));
}

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;

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

You should covert String to float. It is working.

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

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

tv.setText(result); 

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;


You can also do it one line:

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

Reading from order of execution

  1. grab the view using findViewById(R.id.button1)
  2. use ((Button)______) to cast the View as a Button
  3. Call .GetText() to get the text entry from Button
  4. Call .toString() to convert the Character Varying to a String
  5. Call .ReplaceAll() with "[\\D]" to replace all Non Digit Characters with "" (nothing)
  6. Call Integer.parseInt() grab and return an integer out of the Digit-only string.

Try this code it's really working.

int number = 0;
try {
    number = Integer.parseInt(YourEditTextName.getText().toString());
} catch(NumberFormatException e) {
   System.out.println("parse value is not valid : " + e);
} 

The much simpler method is to use the decode method of Integer so for example:

int helloInt = Integer.decode(hello);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to android-edittext

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Design Android EditText to show error message as described by google Change EditText hint color when using TextInputLayout How to change the floating label color of TextInputLayout The specified child already has a parent. You must call removeView() on the child's parent first (Android) Edittext change border color with shape.xml Changing EditText bottom line color with appcompat v7 Soft keyboard open and close listener in an activity in Android EditText underline below text property Custom designing EditText