Android EditText判断输入的字符串是否为数字(包含小数点)

时间:2023-03-09 07:31:25
Android  EditText判断输入的字符串是否为数字(包含小数点)

有时候项目需要获取EditText所输入的字符串为纯数字(含小数),一般情况下在xml中设置EditText的的属性(我是直接设置digits为数字和小数点,即digits="0123456789."),或者在代码中设置

mEd.setKeyListener(DigitsKeyListener.getInstance("0123456789."));

但是发现在三星手机中,弹出的键盘是数字键盘,但是只有数字没有小数点,这就很难受了,所以上网搜索判断字符串的方法,亲测有效,便予以记录。

上代码:

/**
* 判断字符串是否是数字
*/
public static boolean isNumber(String value) {
return isInteger(value) || isDouble(value);
}
/**
* 判断字符串是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
} /**
* 判断字符串是否是浮点数
*/
public static boolean isDouble(String value) {
try {
Double.parseDouble(value);
if (value.contains("."))
return true;
return false;
} catch (NumberFormatException e) {
return false;
}
}

致谢:https://blog.****.net/qq_36255612/article/details/53585786