making EditText to show only two decimal places
You can simply use DecimalFormat
DecimalFormat format = new DecimalFormat("##.##");
String formatted = format.format(22.123);
editText.setText(formatted);
You will get result in EditText
as 22.12
Here is a solution that will limit the user while typing in the edit text.
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint=2;
final int maxDigitsAfterDecimalPoint=2;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches(
"(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
)) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
};
mEdittext.setFilters(new InputFilter[] { filter });
e.g., 12.22 so only 2 digits before and two digits after the decimal ponit will be allowed to be entered.