Mostafa Imran
Mostafa Imran

Reputation: 668

decimal input filter android

I want to make an EditText to take decimal values where 2 digits after decimal point would be allowed(optional). Values can be:

xxxx

xxxx.x

xx.xx

.xx

.x

x.x

I've tried so many solutions found in S/O and I've found proper regex to meet my solution. But none is fulfilling my requirements. some solution meets requirement but doesn't allow to edit before decimal point. Suppose, when edittext value is .xx then can't edit before decimal point(.).

can anyone point out the proper solution.

N.B.: using maxLength property in EditText.

Upvotes: 3

Views: 3361

Answers (1)

Pradeep Gupta
Pradeep Gupta

Reputation: 1770

try this,

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;
        }


    }

and set filter to Edit Text

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

Upvotes: 2

Related Questions