Arunraj
Arunraj

Reputation: 31

How to restrict the user did not enter more than two digits after decimal point?

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?

Upvotes: 2

Views: 1317

Answers (3)

Abubakar Rafi
Abubakar Rafi

Reputation: 91

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

Upvotes: 2

Okky
Okky

Reputation: 10466

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

Upvotes: 3

Ragunath Jawahar
Ragunath Jawahar

Reputation: 19743

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.

Upvotes: 1

Related Questions