Edittext判断输入是否为数字(包含小数点)

在开发中EditText总会要求输入限制,数字?个数?几行?

1.在限制输入类型为double的数字时就需要做两步判断,

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numeric="decimal" />
 

在布局中定义EditText的时候设置为只能输入数字,设置数字的时候可以直接设置android:numeric="decimal" ;

然后再进行具体判断

/**
 * 判断字符串是否是数字
 */
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;
    }
}

2.限制输入小数位数

需要给EditText设置TextWatcher,在输入的时候进行判断

TextWatcher mTextWatcher = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String temp = s.toString();
        int posDot = temp.indexOf(".");
        if (posDot <= 0) return;
        if (temp.length() - posDot - 1 > 4)
        {
            s.delete(posDot + 5, posDot + 6);
        }
    }
};
 

希望能帮助到小伙伴们……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个小狼娃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值