我想使用 TextWatcher 为 EditText 添加 3 位小数的货币格式在开始时,值为 0.000,数字应从右向左更改
例如:如果我按 1,2,3,4,5 的订单值应该显示为这个 12.345
以下代码仅适用于小数点后 2 位。请任何人帮助我如何将此代码更改为小数点后 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,并将NumberFormat
setMinimumFractionDigits
为 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) { }
}