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?
Asked
Active
Viewed 7,413 times
2
-
Check My Answer [Here](https://stackoverflow.com/a/47649705/6444297). – Alireza Noorali Sep 29 '18 at 17:04
2 Answers
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
-
-
please accept the answer if it works.so that it will helpful to others. – Chandra Sharma Sep 16 '15 at 05:20
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