0

I'm new to Android development and I came into some issues trying to limit digits after period to 4 digits only.

I created EditText:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal|numberSigned"
        android:ems="10"
        android:id="@+id/myEdit"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />

And it allows only one dot and numbers what's exactly what I want. But also I need it to allow only 4 digits max after the period. How exactly can I achieve this?

Vadym
  • 548
  • 2
  • 8
  • 21

1 Answers1

-1

First create a class.

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

        }

Then from your onCreate method set a new filter like to your edit text like this:

EditText myEdit = (EditText)findViewById(R.id.myEdit);
myEdit.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,1)});

That's it. You have solved your problem. :)

Tushar Monirul
  • 4,944
  • 9
  • 39
  • 49