How to format a String number into a US phone number format

I wouldn’t use this functionality to check if the text was changed:

if (before < after)

Just given the case someone uses copy-paste to replace the phone number or marks one digit before replacing it.
Better save your text somewhere and if !oldtext.equals(s.toString()) continue.

Assuming editText is your Textbox. Code is also untested, use at your own risk.

    public void afterTextChanged(Editable s) {
                editText.removeTextChangedListener(this);
                if (before < after) {
                    if (s.length() == 4 && s.charAt(0) == '1') {
                        long phoneFmt = Long.parseLong(s.toString().replaceAll("[^\\d]", ""),10);

DecimalFormat phoneDecimalFmt = new DecimalFormat("0000000000");
String phoneRawString= phoneDecimalFmt.format(phoneFmt);

java.text.MessageFormat phoneMsgFmt=new java.text.MessageFormat("({0})-{1}-{2}");
    //suposing a grouping of 3-3-4
String[] phoneNumArr={phoneRawString.substring(0, 3),
          phoneRawString.substring(3,6),
          phoneRawString.substring(6)};


                        editText.setText(phoneMsgFmt.format(phoneNumArr));
                        editText.setSelection(editText.getText().toString().length());
                    }
                }

                editText.addTextChangedListener(this);
            }

Browse More Popular Posts

Leave a Comment