美文网首页
Android EditText判断输入的字符串是否为数字(包

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

作者: 哇哇_刘 | 来源:发表于2019-10-11 09:41 被阅读0次

有时候项目需要获取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

相关文章

网友评论

      本文标题:Android EditText判断输入的字符串是否为数字(包

      本文链接:https://www.haomeiwen.com/subject/oemsyctx.html