android - 如何限制用户输入的小数点后不超过两位数?

标签 android decimal restriction

我在 ListView 中有编辑文本。如果用户在小数点后输入超过两位数,我想限制他们。现在它允许 n 个数字。如何在不使用模式的情况下限制用户输入的小数点后不超过两位数?

最佳答案

我们可以使用正则表达式 (regex) 如下:

public class DecimalDigitsInputFilter implements InputFilter {

    Pattern mPattern;

    public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
        mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            Matcher matcher=mPattern.matcher(dest);       
            if(!matcher.matches())
                return "";
            return null;
        }

    }

要使用它,请执行以下操作:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

关于android - 如何限制用户输入的小数点后不超过两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12909975/

相关文章:

c# - 根据十进制长度确定调用哪个函数

android - 公式 px 到 dp,dp 到 px android

android - 安装 Scarlet 时重复依赖项

android - 图库在 Gallery BaseAdapter 中的 notifydatasetchanged 上闪烁

r - 如何在十进制和十六进制之间转换?

javascript - 按年龄限制访问 FB 应用程序

android - 为什么 AWS 不允许我使用 Google Plus 进行身份验证?

将数字四舍五入到 R 中最接近的小数位

javascript - 使用 Intersection 库检测并对对象/路径应用限制

c# - 由特定通用包含接口(interface)参数化的通用容器接口(interface)