简体   繁体   English

如何使用TextWatcher Android将3位小数货币格式添加到edittext

[英]How to add 3 decimal places Currency formatting to edittext Using TextWatcher Android

I want to add 3 decimal places currency formatting to EditText using TextWatcher at the beginning, value is 0.000 and the number should change right to left 我想在开始时使用TextWatcher3个小数位 货币格式添加到EditText ,值是0.000 ,数字应从右向左更改

eg: if I pressed 1,2,3,4,5 in order value should appear as this 12.345 例如:如果我按1,2,3,4,5的顺序值应显示为12.345

following code is worked only for 2 decimal places. 以下代码仅适用于小数点后2位。 Please anyone helps me how to change this code for 3 decimal places or another solution 请任何人帮助我如何将此代码更改为小数点后3位或其他解决方案

 public class CurrencyTextWatcher  implements TextWatcher {
    boolean mEditing;
    Context context;


    public CurrencyTextWatcher() {
        mEditing = false;
    }

    public synchronized void afterTextChanged(Editable s) {

        if(!mEditing) {
            mEditing = true;
            String digits = s.toString().replaceAll("\\D", "");
             NumberFormat nf = NumberFormat.getCurrencyInstance();

            try{
                String formatted = nf.format(Double.parseDouble(digits)/100);
                s.replace(0, s.length(), formatted);
            } catch (NumberFormatException nfe) {
                s.clear();
            }
            mEditing = false;
        }
    }

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

    public void onTextChanged(CharSequence s, int start, int before, int count) { }

}

Divide 1000 instead of 100 and also setMinimumFractionDigits for NumberFormat as 3. 分1000,而不是100,也setMinimumFractionDigitsNumberFormat为3。

public class CurrencyTextWatcher  implements TextWatcher {
    boolean mEditing;
    Context context;


    public CurrencyTextWatcher() {
        mEditing = false;
    }

    public synchronized void afterTextChanged(Editable s) {

        if(!mEditing) {
            mEditing = true;
            String digits = s.toString().replaceAll("\\D", "");
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            nf.setMinimumFractionDigits(3);

            try{
                String formatted = nf.format(Double.parseDouble(digits)/1000);
                s.replace(0, s.length(), formatted);
            } catch (NumberFormatException nfe) {
                s.clear();
            }
            mEditing = false;
        }
    }

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

    public void onTextChanged(CharSequence s, int start, int before, int count) { }

}

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

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