有時候項目需要獲取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.csdn.net/qq_36255612/article/details/53585786