简体   繁体   中英

Limit Decimal Places in EditText

I'm using an EditText Field where the user can specify an amount of money.

I set the inputType to numberDecimal which works fine, except that this allows to enter numbers such as 123.122 which is not perfect for money.

I wrote some custom InputFilter method and it's working like this.User can 5 elements before dot and after dot-two,but not working correctly My goals are:

1) use should input maximum 9999.99

2) If user starting from 0 and second element is also 0,It must replace with.(for example 0.0) and after two elements after dot(like this 0.01) here is a my code

 public class DecimalDigitsInputFilter implements InputFilter {

    Pattern mPattern;
    public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
        mPattern=Pattern.compile("[0-9]*" + (digitsBeforeZero-1) + "}+((\\.[0-9]*" + (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;
    }

}

I'm calling this method like this

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

How I can rewrite my code to solved my issues? thanks

Your constructed regex is all wrong.

The first part of your regex is this expression:

"[0-9]*" + (digitsBeforeZero-1) + "}+"

Say digitsBeforeZero = 5 , that gets you:

[0-9]*4}+

That's not the correct regex. The regex is supposed to be:

[0-9]{1,5}

meaning between 1 and 5 digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM