0

How to restrict an EditText Field to only one decimal point. Let's say the user should enter only one digit/number after the (.)[decimal].

User enters : 1.92 [Its invalid] User enters : 1.9 [Its Valid]

Below is the regular expression i am using.

mPattern = Pattern.compile("[0-9]*+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");

I am having problems with the decimals, user if enter 23.1 its fine, but the same user can enter 2.31.

How can i restrict user to enter only one number/digit after decimal.

avalancha
  • 1,457
  • 1
  • 22
  • 41
theJava
  • 14,620
  • 45
  • 131
  • 172
  • 1
    This question covers quite the same issue with the decimal restriction. Including solutions with `RegEx` and the `InputFilter Interface`. http://stackoverflow.com/questions/5357455/limit-decimal-places-in-android-edittext – Steve Benett Jun 16 '13 at 11:55

2 Answers2

3

How about using a regular expression for that..

public class DecimalDigitsFilter implements InputFilter {

Pattern pattern;

public DecimalDigitsFilter(int digitsBeforeZero,int digitsAfterZero) {
    pattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) {

    Matcher matcher=pattern.matcher(destination);       
    if(!matcher.matches())
        return "";
    return null;
   }
}

And then call it as..

editText.setFilters(new InputFilter[] {new DecimalDigitsFilter(5,1)}); //5 before point and 1 after point.Change it as your need
ridoy
  • 6,274
  • 2
  • 29
  • 60
0

Add TextWatcher to the textView and use it's methods to prevent typing after dot more then one number.

Lingviston
  • 5,479
  • 5
  • 35
  • 67