如何将字符串转换为整数?
我有一个文本框,让用户输入一个数字:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
这个值被赋值给字符串hello。
我想把它转换成一个整数,这样我就能得到他们输入的数字;稍后将在代码中使用它。
是否有方法将EditText转换为整数?这样就跳过了中间人。如果不是,字符串到整数就可以了。
如何将字符串转换为整数?
我有一个文本框,让用户输入一个数字:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
这个值被赋值给字符串hello。
我想把它转换成一个整数,这样我就能得到他们输入的数字;稍后将在代码中使用它。
是否有方法将EditText转换为整数?这样就跳过了中间人。如果不是,字符串到整数就可以了。
当前回答
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
其他回答
你应该将String转换为float。它正在起作用。
float result = 0;
if (TextUtils.isEmpty(et.getText().toString()) {
return;
}
result = Float.parseFloat(et.getText().toString());
tv.setText(result);
将字符串转换为int的最佳方法是:
EditText et = (EditText) findViewById(R.id.entry1);
String hello = et.getText().toString();
int converted=Integer.parseInt(hello);
int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());
使用正则表达式:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
输出:
i=123;
j=123;
k=123;
请参阅Integer类和静态parseInt()方法:
http://developer.android.com/reference/java/lang/Integer.html
Integer.parseInt(et.getText().toString());
你将需要捕捉NumberFormatException,尽管在解析时遇到问题,所以:
int myNum = 0;
try {
myNum = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}