Android编辑文字十进制格式

时间:2017-02-02 07:20:37

标签: android android-studio android-edittext decimalformat

我可以问一下如何格式化字符串值,例如5000000.005,000,000.00?显然我正在为Android应用程序做货币相关的东西,我可以设法只将字符串值5000000格式化为5,000,000而不使用编辑文本中的点分隔符。我想存储字符串值以供以后用于parseDouble,这样我将需要计算并有一些小数。我设法用逗号分隔符,但任何想法如何使点也显示在编辑文本中? 以下是我的代码:

amountText.addTextChangedListener(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) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                amountText.removeTextChangedListener(this);
                if(!amountText.getText().toString().equals(""))
                {
                    try {
                        String editText = amountText.getText().toString();
                        String newStr = editText.replace("$", "").replace(",", "");
                        customer.getProperty().get(groupPosition).setAmount(newStr);
                        String formattedString = formatString(customer.getProperty().get(groupPosition).getAmount());
                        amountText.setText(formattedString);
                        amountText.setSelection(amountText.getText().length());
                        // to place the cursor at the end of text
                    } catch (NumberFormatException nfe) {
                        nfe.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                amountText.addTextChangedListener(this);
            }
        });

public String formatString(String s)
{
        String givenstring = s.toString();
        Long longval;
        if (givenstring.contains(",")) {
            givenstring = givenstring.replaceAll(",", "");
        }
        longval = Long.parseLong(givenstring);
        DecimalFormat formatter = new DecimalFormat("#,###,###");
        String formattedString = formatter.format(longval);
        return formattedString;
}

我已经测试过使用parseDouble,但是当我输入"。"在EditText中,它只是不会出现,如果我使用长变量,它将给出错误的格式和错误。 (java.lang.NumberFormatException:无效长:" 500000.00")。所有值都以字符串形式完成,稍后处理我将在进行计算时解析该值。 感谢您,感谢任何人的指导,如果有与我无法找到解决方案相似的帖子,我会道歉。

2 个答案:

答案 0 :(得分:0)

试试这个:

public void afterTextChanged(Editable view) {
    String s = null;
    try {
        // The comma in the format specifier does the trick
        s = String.format("%,d", Long.parseLong(view.toString()));
    } catch (NumberFormatException e) {
    }
    // Set s back to the view after temporarily removing the text change listener
}

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

答案 1 :(得分:0)

这是有效的&经过充分测试的代码只需复制&粘贴试试

TextWatcher amountTextWatcher = 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) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                    int cursorPosition = etAmount.getSelectionEnd();
                    String originalStr = etAmount.getText().toString();

                    //To restrict only two digits after decimal place
                    etAmount.setFilters(new InputFilter[]{new MoneyValueFilter(Integer.parseInt(2))});

                try {
                        etAmount.removeTextChangedListener(this);
                        String value = etAmount.getText().toString();

                        if (value != null && !value.equals("")) {
                            if (value.startsWith(".")) {
                                etAmount.setText("0.");
                            }
                            if (value.startsWith("0") && !value.startsWith("0.")) {
                                etAmount.setText("");
                            }
                            String str = etAmount.getText().toString().replaceAll(",", "");
                            if (!value.equals(""))
                                etAmount.setText(getDecimalFormattedString(str));

                            int diff = etAmount.getText().toString().length() - originalStr.length();
                            etAmount.setSelection(cursorPosition + diff);
                        }
                        etAmount.addTextChangedListener(this);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        etAmount.addTextChangedListener(this);
                    }
                }
            }
        };
        etAmount.addTextChangedListener(amountTextWatcher);

以下是将逗号分隔符添加到十进制数

的方法
/**
     * Get decimal formated string to include comma seperator to decimal number
     *
     * @param value
     * @return
     */
    public static String getDecimalFormattedString(String value) {
        if (value != null && !value.equalsIgnoreCase("")) {
            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++;
            }
        }
        return "";
    }

在edittext中仅限小数位后的两位数的方法

/**
     * Restrict digits after decimal point value as per currency
     */
    class MoneyValueFilter extends DigitsKeyListener {
        private int digits;

        public MoneyValueFilter(int i) {
            super(false, true);
            digits = i;
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            CharSequence out = super.filter(source, start, end, dest, dstart, dend);

            // if changed, replace the source
            if (out != null) {
                source = out;
                start = 0;
                end = out.length();
            }

            int len = end - start;

            // if deleting, source is empty
            // and deleting can't break anything
            if (len == 0) {
                return source;
            }

            int dlen = dest.length();

            // Find the position of the decimal .
            for (int i = 0; i < dstart; i++) {
                if (dest.charAt(i) == '.') {
                    // being here means, that a number has
                    // been inserted after the dot
                    // check if the amount of digits is right
                    return getDecimalFormattedString((dlen - (i + 1) + len > digits) ? "" : String.valueOf(new SpannableStringBuilder(source, start, end)));
                }
            }

            for (int i = start; i < end; ++i) {
                if (source.charAt(i) == '.') {
                    // being here means, dot has been inserted
                    // check if the amount of digits is right
                    if ((dlen - dend) + (end - (i + 1)) > digits)
                        return "";
                    else
                        break; // return new SpannableStringBuilder(source,
                    // start, end);
                }
            }

            // if the dot is after the inserted part,
            // nothing can break
            return getDecimalFormattedString(String.valueOf(new SpannableStringBuilder(source, start, end)));
        }
    }