0

I have an EditBox in which I allow users to enter numbers. But my question is how can I restrict the user to enter not more than three-digit numbers before the decimal point and not more that one digit after decimal point eg: 22.1, 333.3, 34 but if the user try to enter 6666.777 it will not allowed them to enter.

Please help me to solve this out. If possible with an example

Waldi
  • 39,242
  • 6
  • 30
  • 78
AndroidDev
  • 4,521
  • 24
  • 78
  • 126

2 Answers2

2

Use InputFilter to restrict user. Here is another such topic. Limit Decimal Places in Android EditText

Modify for you own. I've used this for my own.

private class DecimalDigitsInputFilter implements InputFilter
{

    Pattern mPattern;

    public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero)
    {
        mPattern = Pattern.compile("[0-9]{0,3}\\.[0-9]{0,1}||[0-9]{1,3}");
    }

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

}

Now set the filter

youEditText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(3,1)});
Community
  • 1
  • 1
Shaiful
  • 5,643
  • 5
  • 38
  • 41
  • Is it possible to do using regular expression...but what will be the pattern for my conditions – AndroidDev Apr 23 '12 at 10:11
  • Yes. possible. :). Edited my ans. – Shaiful Apr 23 '12 at 10:11
  • Hey Shaiful..your codes work but after 333 it will not allow me to enter. what i what i want is to allow user to enter three digit before decimal and one digit after decimal. In ur code it allow me to enter digit after decimal point only when there is 2 digit before decimal point..but my requirement is it always allow user to enter one digit after decimal point if the digit before decimal point is not more then three. More ever it doesn't allow user to enter number that start with zero like 0.1, 0, .1 etc – AndroidDev Apr 23 '12 at 10:30
  • Hi, Changed my regular expression. Let me know if its working. – Shaiful Apr 23 '12 at 10:52
  • Now it doesn't allow me to enter anything. – AndroidDev Apr 23 '12 at 11:00
  • This Regex is working fine `"[0-9]{0,3}\\.[0-9]{0,1}||[0-9]{1,3}"` in web (http://www.regexplanet.com/advanced/java/index.html) but not in EditText. I don't know why. :( – Shaiful Apr 23 '12 at 11:30
0
private boolean decimalValidation(String str,int decimalDigitCount){
        int positionFromLeft=INT_MAX;
        try {
            if (str.contains(".")) {
                positionFromLeft = str.length() - str.indexOf(".") - 1;
            }else positionFromLeft = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return positionFromLeft <= decimalDigitCount;
    }

Note: str has to be number in string format.