2

I want to add commas between each 1,000 in EditText, so the user wont have to "guess" if it is 10,000 or 100,000. In EditText when you input a number it is displayed like 10000 but I want to display it like 10,000. How can that be done?

Anders
  • 8,307
  • 9
  • 56
  • 88
Rejain
  • 31
  • 1
  • 2

2 Answers2

6

You have to add TextChangedListner to your edittext .i.e

          et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                et.removeTextChangedListener(this);

                try {
                    String givenstring = s.toString();
                    Long longval;
                    if (givenstring.contains(",")) {
                        givenstring = givenstring.replaceAll(",", "");
                    }
                    longval = Long.parseLong(givenstring);
                    DecimalFormat formatter = new DecimalFormat("#,###,###");
                    String formattedString = formatter.format(longval);
                    et.setText(formattedString);
                    et.setSelection(et.getText().length());
                    // to place the cursor at the end of text
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                et.addTextChangedListener(this);

            }
        });

Note : Make sure that your edittext inputtype is number. i.e android:inputType="number"

Chandra Sharma
  • 1,339
  • 1
  • 12
  • 26
0

Attach a TextChangedListener to EditText using :

editText.addTextChangedListener();

Refer the below javadoc of TextWatcher : http://developer.android.com/reference/android/text/TextWatcher.html

Constantine
  • 1,356
  • 14
  • 19