简体   繁体   English

将EditText格式化为整数的货币

[英]Format EditText to currency with whole numbers

All- I have a TextWatcher that formats an EditText to currency format: 全部 - 我有一个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);
    }
}

This works great, the problem is that my EditText only needs whole numbers so I do not the user to be able to enter cents. 这很好用,问题是我的EditText只需要整数,所以我不能让用户输入美分。 So instead of 0.01 than 0.12 than 1.23 than 12.34, I want 1 than 12 than 123 than 1,234. 因此,与12.34相比,我想要的不是0.1比0.12而不是1.23。 How can I get rid of the decimal point but keep the commas? 如何摆脱小数点但保留逗号? Thank you. 谢谢。

If you don't mind removing the period and trailing zeroes, you could do this: 如果你不介意删除句点和尾随零,你可以这样做:

    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) {
        }
    });

This will set the number formatter's maximum fraction digits to zero, removing all trailing zeroes and the period. 这会将数字格式化程序的最大小数位数设置为零,删除所有尾随零和周期。 I also removed the division by 100 so that all entered numbers are integers. 我还将除法除以100,以便所有输入的数字都是整数。

Also make sure that your EditText's inputType is "number" or this will crash if the user tries to enter a non-numeric character. 还要确保EditText的inputType是“number”,否则如果用户尝试输入非数字字符,这将会崩溃。

Hexar's answer was useful but it lacked error detection when the user deleted all the numbers or moved the cursor. Hexar的答案很有用,但当用户删除所有数字或移动光标时,它缺少错误检测。 I built on to his answer and an answer here to form a complete solution. 我建立了他的答案和答案以形成一个完整的解决方案。 It may not be best practice due to setting the EditText in the onTextChanged() method but it works. 由于在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();
                }
            }
        }

A quick way to ensure the user doesn't enter invalid information is to edit the xml. 确保用户不输入无效信息的快速方法是编辑xml。 For my program, a limit of 6 number characters was set. 对于我的程序,设置了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"/>

Why don't you format the amount using currencyFormat and then take out the .00 from the String. 为什么不使用currencyFormat格式化金额,然后从String中取出.00

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

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

etProductCost.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 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) {}
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM