making EditText to show only two decimal places

前端 未结 4 1019
礼貌的吻别
礼貌的吻别 2021-01-12 12:28

i want to show only two decimal places in my edit text, ofc i wanna show currency in edit text but limiting its value to 2 digits after decimal.

I have seen some sol

4条回答
  •  爱一瞬间的悲伤
    2021-01-12 12:41

    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.

提交回复
热议问题