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

后端 未结 13 2035
花落未央
花落未央 2020-11-27 05:21

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 autom

13条回答
  •  爱一瞬间的悲伤
    2020-11-27 05:57

    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
    }
    

提交回复
热议问题