我正在开发Android项目。 我需要在EditText中格式化实时编辑中的数字
例如:
我现在所做的不行:/,我已将EditText设置为仅数字输入。
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
try {
//String str = s.toString();
//String str = String.format("%,d", s.toString()
// .replaceAll(",", ""));
editText.removeTextChangedListener(this);
String str = s.toString().replaceAll(",", "");
String edit = "";
if(str.length()==2)
{
int pos = editText.getSelectionStart();
String firstChar = str.substring(0, 1);
String secondChar = str.substring(1, str.length()-1);
edit = firstChar+ "," +secondChar;
}
else
{
edit = str;
}
editText.setSelection(edit.length());
editText.setText(edit);
editText.addTextChangedListener(this);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
public String doubleToStringNoDecimal(double d) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);;
formatter .applyPattern("#,###");
return formatter.format(d);
}
@Override
public void beforeTextChanged(CharSequence c, int arg1, int arg2, int arg3) {
// String str = editText.getText().toString();
// len = str.length();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// String str = editText.getText().toString();
}
});
答案 0 :(得分:3)
你可以用你的代码尝试这个:
String num = "1234567";
num = new StringBuilder(num).reverse().toString().replaceAll("(\\d{3})", "$1,");
num = new StringBuilder(num).reverse().toString().replaceAll("^,|,$", "");
System.out.println(num);
输出:
1,234,567