2

I have edittext in listview. I want to restrict the user if they enter more than two digits after the decimal point. Now it allowing n number of numbers. How to restrict the user did not enter more than two numbers after decimal point without using pattern?

Arunraj
  • 31
  • 6

3 Answers3

3

We can use a regular expression ( regex ) as follows:

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

    }

To use it do:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
Sakthimuthiah
  • 2,606
  • 6
  • 26
  • 41
Okky
  • 10,338
  • 15
  • 75
  • 122
2

It might be late but i am posting my solution hope it will works for someone

in Your Text Watcher Method afterTextChanged do this .

public void afterTextChanged(Editable s) {

                if(mEditText.getText().toString().contains(".")){
                    String temp[] =  mEditText.getText().toString().split("\\.");
                    if(temp.length>1) {
                        if (temp[1].length() > 3) {
                            int length = mEditText.getText().length();
                            mEditText.getText().delete(length - 1, length);
                        }
                    }
                }
    }
1

You can use a TextWatcher and in the afterTextChanged method use a regular expression to match the required text and delete the extra numbers are they are entered.

Ragunath Jawahar
  • 19,513
  • 22
  • 110
  • 155