gpt4 book ai didi

android - 实时编辑后如何在android EditText中格式化数字

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:47:28 24 4
gpt4 key购买 nike

我有一个 EditText,用户应该在其中输入一个包括小数的数字,我希望将千位分隔符自动添加到输入数字上 我尝试了其他几种方法,但有些方法不允许 float ,所以我想到了这个仅当字符串输入未被实时编辑为可能具有千位分隔符并且错误似乎源于 s.replace();

    am2 = new TextWatcher(){
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) {
if (s.toString().equals("")) {
amount.setText("");
value = 0;
}else{
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < amount2.getText().toString().length() ; i++) {
c = amount2.getText().toString().charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
value = Double.parseDouble(strBuff.toString());
reverse();
NumberFormat nf2 = NumberFormat.getInstance(Locale.ENGLISH);
((DecimalFormat)nf2).applyPattern("###,###.#######");
s.replace(0, s.length(), nf2.format(value));
}
}
};

最佳答案

这个类解决了这个问题,允许小数输入并添加了千位分隔符。

    public class NumberTextWatcher implements TextWatcher {

private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;

private EditText et;

public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###.##");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false;
}

@SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";

public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);

try {
int inilen, endlen;
inilen = et.getText().length();

String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}

et.addTextChangedListener(this);
}

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

public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}

}

来源:http://blog.roshka.com/2012/08/android-edittext-with-number-format.html

关于android - 实时编辑后如何在android EditText中格式化数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12542211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com