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

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

我想使用 [=18] 添加 3 个小数位 货币格式 EditText =]TextWatcher 开始时,值为 0.000 并且数字应 从右到左变化

例如:如果我按顺序按 1、2、3、4、5,值应该显示为 12.345

以下代码仅适用于小数点后两位。请任何人帮助我 如何将此代码更改为小数点后 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) { }

}

除以 1000 而不是 100 并且 setMinimumFractionDigits 对于 NumberFormat 为 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) { }

}