Like others said, I added this class in my project and set the filter to the EditText
I want.
The filter is copied from @Pixel's answer. I'm just putting it all together.
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter() {
mPattern = Pattern.compile("([1-9]{1}[0-9]{0,2}([0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)");
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String formatedSource = source.subSequence(start, end).toString();
String destPrefix = dest.subSequence(0, dstart).toString();
String destSuffix = dest.subSequence(dend, dest.length()).toString();
String result = destPrefix + formatedSource + destSuffix;
result = result.replace(",", ".");
Matcher matcher = mPattern.matcher(result);
if (matcher.matches()) {
return null;
}
return "";
}
}
Now set the filter in your EditText
like this.
mEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter()});
Here one important thing is it does solves my problem of not allowing showing more than two digits after the decimal point in that EditText
but the problem is when I getText()
from that EditText
, it returns the whole input I typed.
For example, after applying the filter over the EditText
, I tried to set input 1.5699856987. So in the screen it shows 1.56 which is perfect.
Then I wanted to use this input for some other calculations so I wanted to get the text from that input field (EditText
). When I called mEditText.getText().toString()
it returns 1.5699856987 which was not acceptable in my case.
So I had to parse the value again after getting it from the EditText
.
BigDecimal amount = new BigDecimal(Double.parseDouble(mEditText.getText().toString().trim()))
.setScale(2, RoundingMode.HALF_UP);
setScale
does the trick here after getting the full text from the EditText
.