Paul Asiimwe Paul Asiimwe - 1 year ago 253
Android Question

How to Automatically add thousand separators as number is input in EditText

Im creating a convertor application, I want to set the EditText so that when the user is inputting the number to be converted, a thousand separator (,) should be added automaticaaly in realtime to the number once it increaments by 3 figures.....thousand, million, billion etc
and when erased to below 4 figures the number goes back to normal.
Any help?
Thank You.

Answer Source

You can use String.format() in a TextWatcher. The comma in the format specifier does the trick.

This does not work for floating point input. And be careful not to set an infinite loop with the TextWatcher.

public void afterTextChanged(Editable view) {
    String s = null;
    try {
        // The comma in the format specifier does the trick
        s = String.format("%,d", Long.parseLong(view.toString()));
    } catch (NumberFormatException e) {
    // Set s back to the view after temporarily removing the text change listener