将EditText格式化为整数的货币

时间:2012-11-21 01:16:08

标签: java android formatting android-edittext

清一色 我有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只需要整数,所以我不能让用户输入分数。因此,与12.34相比,我想要的不是0.1比0.12而不是1.23。 如何摆脱小数点但保留逗号?谢谢。

4 个答案:

答案 0 :(得分:8)

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

    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为" number"如果用户试图输入非数字字符,则会崩溃。

答案 1 :(得分:3)

Hexar的答案很有用,但当用户删除所有数字或移动光标时,它没有检测到错误。我建立了他的答案和答案here,以形成一个完整的解决方案。由于在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"/>

答案 2 :(得分:0)

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

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

currencyFormat.get()。format(&lt; your_amount_here&gt;)

答案 3 :(得分:0)

etProductCost.addTextChangedListener(new TextWatcher(){             @覆盖             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) {}
    });