Unable to add decimal with EditText inputType="number" Android

2.6k views Asked by At

The dot or comma button is disabled when inputType="number" or inputType="number|Decimal" is pressed. It failed to work with android:digits="0123456789.," also.

The EditText contains a textwatcher which format the number. The textwather is as follows:

mEditWithdrawalAmount.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {

        if (!s.toString().equals(current)) {
            mEditWithdrawalAmount.removeTextChangedListener(this);

            String replaceable = String.format("[%s .\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
            String cleanString = s.toString().replaceAll(replaceable, "").replace("R","").replace(",","");
            double parsed;
            try {
                parsed = Double.parseDouble(cleanString);
            } catch (NumberFormatException e) {
                parsed = 0.00;
            }

            String formatted = Utils.formatCurrency(parsed);

            current = formatted;
            mEditWithdrawalAmount.setText(formatted);
            mEditWithdrawalAmount.setSelection(formatted.length());

            // Do whatever you want with position
            mEditWithdrawalAmount.addTextChangedListener(this);
        }
    }
});

The problem is the edittext must allow numbers with decimal place also.

  • Actual result is : R1000 000
  • Desired result is R1000 000.00 or R1000 000.40
3

There are 3 answers

1
Pratik Gondil On

Hey check this code.

android:inputType="numberDecimal"

Hope this help.

0
Ali Asheer On

You can use input filter like this:

InputFilter filter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            if(source.equals("")){ // for backspace
                return source;
            }

            if(source.toString().matches("[0-9.]+")){
                return source;
            }
            return "";
        }
    };

Then set it to your edit text

 topedittext.setFilters(new InputFilter[] { filter,new InputFilter.LengthFilter(30) });
0
Apoorv Mehrotra On

try this out: it is a sample code

 amountEditText.setRawInputType(Configuration.KEYBOARD_12KEY);
    amountEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
            {
                String userInput= ""+s.toString().replaceAll("[^\\d]", "");
                StringBuilder cashAmountBuilder = new StringBuilder(userInput);

                while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                    cashAmountBuilder.deleteCharAt(0);
                }
                while (cashAmountBuilder.length() < 3) {
                    cashAmountBuilder.insert(0, '0');
                }
                cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
                cashAmountBuilder.insert(0, '$');

                amountEditText.setText(cashAmountBuilder.toString());
                // keeps the cursor always to the right
                Selection.setSelection(amountEditText.getText(), cashAmountBuilder.toString().length());

            }

        }
    });

or this one it works for me

I've implemented everything in the onFocusChangedListener. Also be sure to set the EditText input type to "number|numberDecimal".

Changes are: If input is empty then replace with "0.00". If input has more than two decimals of precision, then cast down to two decimals. Some minor refactoring.

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override public void onFocusChange(View v, boolean hasFocus) {
    if (!hasFocus) {
        String userInput = ET.getText().toString();

        if (TextUtils.isEmpty(userInput)) {
            userInput = "0.00";
        } else {
            float floatValue = Float.parseFloat(userInput);
            userInput = String.format("%.2f",floatValue);
        }

        editText.setText(userInput);
    }
}
});