making EditText to show only two decimal places

前端 未结 4 982
礼貌的吻别
礼貌的吻别 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:31

    Input:

     mBinding.etPriceUpdate.setText = getString(R.string.txt_rupees) + " " + "%.2f".format(firstNum!!.toDouble() * secondNum.toDouble())
    

    Output:

    ₹ 4567.54

    This will format the floating-point number 1.23456 up to 2 decimal places because we have used two after the decimal point in formatting instruction %.2f, f is for floating-point number, which includes both double and float data type in Java. Don't try to use "d" for double here, because that is used to format integer and stands for decimal in formatting instruction. By the way, there is a catch here, format() method will also arbitrarily round the number. For example, if you want to format 1.99999 up-to 2 decimal places then it will return 2.0 rather then 1.99, as shown below.

    0 讨论(0)
  • 2021-01-12 12:38

    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

    0 讨论(0)
  • 2021-01-12 12:39

    You just need to assign setKeyListener() to your EditText.

    myEditText.setKeyListener(DigitsKeyListener.getInstance(true,true));
    

    Returns a DigitsKeyListener that accepts the digits 0 through 9, plus the minus sign (only at the beginning) and/or decimal point (only one per field) if specified.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题