Converting a string to an integer on Android

2019-01-03 05:00发布

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.

12条回答
ゆ 、 Hurt°
2楼-- · 2019-01-03 05:34
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
查看更多
淡お忘
3楼-- · 2019-01-03 05:34

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); 
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-03 05:36

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]", ""));
}
查看更多
干净又极端
5楼-- · 2019-01-03 05:47

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;

查看更多
叼着烟拽天下
6楼-- · 2019-01-03 05:47

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

int helloInt = Integer.decode(hello);
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-03 05:47

Kotlin

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

Java

String num = "10";
Integer.parseInt(num );
查看更多
登录 后发表回答