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.csdn.net/qq_36255612/article/details/53585786


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM