Treatment of decimal places EditText

1

I need to set a number of decimal places for EditText on Android. For this I used InputFilter as I show below:

public NumeroFormatado(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;
}

And in my Activity I define:

editValor = (EditText) findViewById(R.id.editValor);
editValor.setFilters(new InputFilter[] {new NumeroFormatado(10,2)});

But when I enter a value such as 22.85 and click the button next to the keyboard, the field loses the decimal places. If I tell 22.80 it works normally.

    
asked by anonymous 27.02.2018 / 12:37

1 answer

1

Only one adjustment was made in InputFilter and the class was as shown below:

public class NumeroFormatado implements InputFilter{    

 private int mDigitsBeforeZero;
 private int mDigitsAfterZero;
 private Pattern mPattern;

 private static final int DIGITS_BEFORE_ZERO_DEFAULT = 100;
 private static final int DIGITS_AFTER_ZERO_DEFAULT = 100;

 public NumeroFormatado(Integer digitsBeforeZero, Integer digitsAfterZero) {
    this.mDigitsBeforeZero = (digitsBeforeZero != null ? digitsBeforeZero : DIGITS_BEFORE_ZERO_DEFAULT);
    this.mDigitsAfterZero = (digitsAfterZero != null ? digitsAfterZero : DIGITS_AFTER_ZERO_DEFAULT);
    mPattern = Pattern.compile("-?[0-9]{0," + (mDigitsBeforeZero) + "}+((\.[0-9]{0," + (mDigitsAfterZero)
            + "})?)||(\.)?");
}

 @Override
 public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    String replacement = source.subSequence(start, end).toString();
    String newVal = dest.subSequence(0, dstart).toString() + replacement
            + dest.subSequence(dend, dest.length()).toString();
    Matcher matcher = mPattern.matcher(newVal);
    if (matcher.matches())
        return null;

    if (TextUtils.isEmpty(source))
        return dest.subSequence(dstart, dend);
    else
        return "";
 }
}

In Activity continues the same call:

editValor = (EditText) findViewById(R.id.editValor);
editValor.setFilters(new InputFilter[] {new NumeroFormatado(10,2)});
    
28.02.2018 / 21:53