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

后端 未结 13 2018
花落未央
花落未央 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:55

    Since i had the same problem i decided to find a solution to it

    Find my function below i hope it helps people finding solution

    securityDeposit.addTextChangedListener(new TextWatcher() {
    
                @Override
                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void beforeTextChanged(CharSequence s, int start,
                        int before, int count) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
                    if (s.toString().trim().length() > 0) {
                        int rentValue = Integer.parseInt(s.toString()
                                .replaceAll(",", ""));
                        StringBuffer rentVal = new StringBuffer();
                        if (rentValue > 10000000) {
                            s.clear();
                            s.append("10,000,000");
                        } else {
    
                            if (s.length() == 4) {
                                char x[] = s.toString().toCharArray();
    
                                char y[] = new char[x.length + 1];
                                for (int z = 0; z < y.length; z++) {
    
                                    if (z == 1) {
                                        y[1] = ',';
    
                                    } else {
                                        if (z == 0)
                                            y[z] = x[z];
                                        else {
                                            y[z] = x[z - 1];
                                        }
                                    }
    
                                }
    
                                for (int z = 0; z < y.length; z++) {
                                    rentVal = rentVal.append(y[z]);
                                }
    
                                s.clear();
                                s.append(rentVal);
    
                            }
    
                        }
                    }
    
                }
            });
    

提交回复
热议问题