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

后端 未结 13 1958
花落未央
花落未央 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 06:01

    This sample app deconstructs formatting numbers clearly.

    To summarize the link above, use a TextWatcher and in the afterTextChanged() method format the EditText view with the following logic:

    @Override
    public void afterTextChanged(Editable s) {
        editText.removeTextChangedListener(this);
    
        try {
            String originalString = s.toString();
    
            Long longval;
            if (originalString.contains(",")) {
                originalString = originalString.replaceAll(",", "");
            }
            longval = Long.parseLong(originalString);
    
            DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
            formatter.applyPattern("#,###,###,###");
            String formattedString = formatter.format(longval);
    
            //setting text after format to EditText
            editText.setText(formattedString);
            editText.setSelection(editText.getText().length());
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    
        editText.addTextChangedListener(this);
    }
    
    0 讨论(0)
提交回复
热议问题