3

所有-我有一个TextWatcher格式化EditText为货币格式的:

private String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if(!s.toString().equals(current)){
        editText$.removeTextChangedListener(this);

       String cleanString = s.toString().replaceAll("[$,.]", "");

       double parsed = Double.parseDouble(cleanString);           
       String formated = NumberFormat.getCurrencyInstance().format((parsed/100));          

       current = formated;
       editText$.setText(formated);
       editText$.setSelection(formated.length());

       editText$.addTextChangedListener(this);
    }
}

这很好用,问题是我EditText只需要整数,所以我不需要用户输入美分。所以不是 0.01 比 0.12 比 1.23 比 12.34,我想要 1 比 12 比 123 比 1,234。我怎样才能摆脱小数点但保留逗号?谢谢你。

4

4 回答 4

9

如果您不介意删除句点和尾随零,您可以这样做:

    mEditText.addTextChangedListener(new TextWatcher() {
        private String current = "";

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals(current)) {
                annualIncomeEntry.removeTextChangedListener(this);

                String cleanString = s.toString().replaceAll("[$,]", "");

                if (cleanString.length() > 0) {
                    double parsed = Double.parseDouble(cleanString);
                    NumberFormat formatter = NumberFormat.getCurrencyInstance();
                    formatter.setMaximumFractionDigits(0);
                    current = formatter.format(parsed);
                } else {
                    current = cleanString;
                }


                annualIncomeEntry.setText(current);
                annualIncomeEntry.setSelection(current.length());
                annualIncomeEntry.addTextChangedListener(this);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    });

这会将数字格式化程序的最大小数位数设置为零,删除所有尾随零和句点。我还删除了除以 100,以便所有输入的数字都是整数。

还要确保您的 EditText 的 inputType 是“数字”,否则如果用户尝试输入非数字字符,这将崩溃。

于 2012-11-21T01:23:19.213 回答
3

Hexar 的答案很有用,但是当用户删除所有数字或移动光标时,它缺乏错误检测。我以他的回答和此处的回答为基础,形成了一个完整的解决方案。由于在 onTextChanged() 方法中设置了 EditText,这可能不是最佳实践,但它可以工作。

    /* don't allow user to move cursor while entering price */
    mEditText.setMovementMethod(null);
    mEditText.addTextChangedListener(new TextWatcher() {
        private String current = "";
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        private double parsed;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals(current)) {
                /* remove listener to prevent stack overflow from infinite loop */
                mEditText.removeTextChangedListener(this);
                String cleanString = s.toString().replaceAll("[$,]", "");

                try {
                    parsed = Double.parseDouble(cleanString);
                }
                catch(java.lang.NumberFormatException e) {
                    parsed = 0;
                }

                formatter.setMaximumFractionDigits(0);
                String formatted = formatter.format(parsed);

                current = formatted;
                mEditText.setText(formatted);

                /* add listener back */
                mEditText.addTextChangedListener(this);
                /* print a toast when limit is reached... see xml below. 
                 * this is for 6 chars */
                if (start == 7) {
                    Toast toast = Toast.makeText(getApplicationContext(), 
                        "Maximum Limit Reached", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            }
        }

确保用户不输入无效信息的一种快速方法是编辑 xml。对于我的程序,设置了 6 个数字字符的限制。

        <!-- it says maxLength 8 but it's really 6 digits and a '$' and a ',' -->
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number|textVisiblePassword"
            android:maxLength="8"
            android:digits="0123456789"
            android:id="@+id/mEditText"
            android:hint="Price"/>
于 2014-12-31T21:18:55.207 回答
0

为什么不使用currencyFormat格式化金额,然后从字符串中取出.00 。

private static final ThreadLocal<NumberFormat> currencyFormat = new ThreadLocal<NumberFormat>() {
        @Override
        protected NumberFormat initialValue() {
            return NumberFormat.getCurrencyInstance();
        }
    };

currencyFormat.get().format(< your_amount_here > )

于 2012-11-21T01:30:49.757 回答
0

etProductCost.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) {
            if (s.toString().length() == 1){
                //first number inserted.
                if (s.toString().equals(getString(R.string.currency_symbol))){
                    //if it is a currecy symbol
                    etProductCost.setText("");
                }else {
                    etProductCost.setText(getString(R.string.currency_symbol) + s.toString());
                    etProductCost.setSelection(s.toString().length());
                }
                return;
            }
            //set cursor position to last in edittext
            etProductCost.setSelection(s.toString().length());
        }

        @Override
        public void afterTextChanged(Editable s) {}
    });
于 2016-11-04T07:12:40.457 回答