“EditText and TextView” formatted with thousands separators (,) in android

末鹿安然 提交于 2019-12-02 01:12:59

You can use

String value=String.format("%,.2f", num );

to parse the number to String with a thousands separator and then set the result to the TextView or EditText that you want

For example :

txt.setText(String.format("%,.2f", num ));
edt.setText(String.format("%,.2f", num ));

Try use this code

        @Override
        public void afterTextChanged(Editable s) {

            try
            {
                edittext.removeTextChangedListener(this);
                String value = edittext.getText().toString();
                if (value != null && !value.equals(""))
                {
                    String str = edittext.getText().toString().replaceAll(",", "");
                    if (value != null && !value.equals(""))
                        Double.valueOf(str).doubleValue();
                    edittext.setText(getDecimalFormat(str));
                    edittext.setSelection(edittext.getText().toString().length());
                }
                edittex.addTextChangedListener(this);
                return;
            }
            catch (Exception localException)
            {
                localException.printStackTrace();
                edittext.addTextChangedListener(this);
            }
        }

 private String getDecimalFormat(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++;
    }
}

hope help you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!