Search code examples
androidandroid-edittext

Add Thousand Separators Automatically While Text Changes in Android EditText


There are many answers out there for the same task I want to accomplish and even I couldn't find any solutions useful in my case

I've seen

Question 1 -- The issue was it is adding commas counting "." (DOT) also as numeric value.

Question 2 -- The issue was it is not showing It's result while text is being changed

Question 3 -- The issue was It is adding 0 continuously after 15th letter.

And many more questions and answers are out there,

But I didn't find anything that meets general requirements for thousand separator.

Is there any useful Tips that helps me adding the thousand separator smoothly as text changed and treats differently for numbers after decimal like as calculator ?

I will appreciate any kind of helps.


Solution

  • I was having the same issue and researched much for the task To get the proper result. So I finally solved the issueand I am providing you my code that'll definitely help you out.

    You can directly copy my codes in your own class, It's fully Tested

    Fetures of the following codes

    • Puts thousand separator as text changes inside EditText.

    • adds 0. Automatically when pressed period (.) At First.

    • Ignores 0 input at Beginning.

    Class Name : NumberTextWatcherForThousand which implements TextWatcher

    import android.text.Editable;
    import android.text.TextWatcher;
    import android.widget.EditText;
    import java.util.StringTokenizer;
    
    /**
     * Created by Shreekrishna on 12/14/2014.
     */
    public class NumberTextWatcherForThousand implements TextWatcher {
    
        EditText editText;
    
    
        public NumberTextWatcherForThousand(EditText editText) {
            this.editText = editText;
    
    
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
    
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            try
            {
                editText.removeTextChangedListener(this);
                String value = editText.getText().toString();
    
    
                if (value != null && !value.equals(""))
                {
    
                    if(value.startsWith(".")){
                        editText.setText("0.");
                    }
                    if(value.startsWith("0") && !value.startsWith("0.")){
                        editText.setText("");
    
                    }
    
    
                    String str = editText.getText().toString().replaceAll(",", "");
                    if (!value.equals(""))
                    editText.setText(getDecimalFormattedString(str));
                    editText.setSelection(editText.getText().toString().length());
                }
                editText.addTextChangedListener(this);
                return;
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
                editText.addTextChangedListener(this);
            }
    
        }
    
        public static String getDecimalFormattedString(String value)
        {
            StringTokenizer lst = new StringTokenizer(value, ".");
            String str1 = value;
            String str2 = "";
            if (lst.countTokens() > 1)
            {
                str1 = lst.nextToken();
                str2 = lst.nextToken();
            }
            String str3 = "";
            int i = 0;
            int j = -1 + str1.length();
            if (str1.charAt( -1 + str1.length()) == '.')
            {
                j--;
                str3 = ".";
            }
            for (int k = j;; k--)
            {
                if (k < 0)
                {
                    if (str2.length() > 0)
                        str3 = str3 + "." + str2;
                    return str3;
                }
                if (i == 3)
                {
                    str3 = "," + str3;
                    i = 0;
                }
                str3 = str1.charAt(k) + str3;
                i++;
            }
    
        }
    
        public static String trimCommaOfString(String string) {
    //        String returnString;
            if(string.contains(",")){
                return string.replace(",","");}
            else {
                return string;
            }
    
        }
    }
    

    Use This Class on your EditText as follows

    editText.addTextChangedListener(new NumberTextWatcherForThousand(editText));
    

    To get the input as plain Text Typed as Double

    Use the trimCommaOfString method of the same class like this

    NumberTextWatcherForThousand.trimCommaOfString(editText.getText().toString());