androidnumber-formattingandroid-input-filterinput-filter

Android : First digit is not displaying when using decimal input filter with NumberFormat


In my android application I am using a decimal input filter to block the number of digits before decimal seperator(.) to 14 and after dot to 4, also using a NumberFormat with US locale to format the amount entered by user.I have noticed 2 problem when i try this as below.


Solution

  • Finally I solved the problem after spending half of the day.I changed my DecimalInputDegitsFilter class ass below which solved both the problem.

            public class DecimalDigitsInputFilter implements InputFilter {
    
            Pattern mPattern;
            int digitsBeforeZero,digitsAfterZero;
    
            public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
                this.digitsBeforeZero = digitsBeforeZero;
                this.digitsAfterZero = 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.toString().replace(",", ""));
                if (!matcher.matches()) {
                    if (dest.toString().contains(".")) {
                        if (dest.toString().substring(dest.toString().indexOf(".")).length() > digitsAfterZero) {
                            return "";
                        }
                        return null;
                    } else if (!Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}").matcher(dest).matches()) {
                        if (!dest.toString().contains(".")) {
                            if (source.toString().equalsIgnoreCase(".")) {
                                return null;
                            }
                        }
                        return "";
                    }
                    return "";
                }
                return null;
            }
        }