Limit Decimal Places in EditText

240 Views Asked by At

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

1

There are 1 best solutions below

4
On

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.