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

后端 未结 13 2061
花落未央
花落未央 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 05:37

    Here i have tested my application code. text-watcher how to add comma in currency thousand, lake currency.

     private TextWatcher textWatcherAmount = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String initial = s.toString();
    
                if (inputEdtHawalaRate == null) return;
    
                if (!TextUtils.isEmpty(initial)) {
    
                    initial = initial.replace(",", "");
    
                    NumberFormat formatter = new DecimalFormat("##,##,###");
    
                    inputEdtHawalaRate.removeTextChangedListener(this);
    
                    double myNumber = Double.parseDouble(initial);
                    String processed = formatter.format(myNumber);
    
                    //Assign processed text
                    inputEdtHawalaRate.setText(processed);
    
                    try {
                        inputEdtHawalaRate.setSelection(processed.length());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
    
                    //Give back the listener
                    inputEdtHawalaRate.addTextChangedListener(this);
    
                }
    
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
            }
        };
    
    
     if (inputEdtHawalaRate != null) {
                inputEdtHawalaRate.addTextChangedListener(textWatcherAmount);
            } 
    

    // getting amount on double type varaible (On textwatcher editetxt value get).

    String amount = Objects.requireNonNull(inputEdtHawalaRate.getText()).toString().trim();
    double hawalaAmount = 0.0;
    
     String[] a = amount.split(",");
                finalAmount = TextUtils.join("", a);
                hawalaAmount = Double.parseDouble(finalAmount);
    

提交回复
热议问题