所以只是一个非常直截了当的问题。我有一个textview,它包含一个数字值(不断更新。所以有一种方法可以用来自动添加一个逗号,如果数字增加了吗?我知道Visual Basic中有一个方法,但我还是很新的android / java平台。
编辑:
String number = textView1.getText().toString();
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###");
String formatted = formatter.format(amount);
textView1.setText(formatted);
这不起作用?
答案 0 :(得分:12)
有效的方式:
private String getFormatedAmount(int amount){
return NumberFormat.getNumberInstance(Locale.US).format(amount);
}
<强>结果:强>
IP 代表输入 OP 代表输出
I / P 10
O / P 10
I / P 100
O / P 100
I / P 1000
至 O / P 1,000
I / P 10000
至 O / P 10,000
I / P 100000
至 O / P 1,00,000
I / P 1000000
至 O / P 10,00,000
希望这会对你有所帮助。
答案 1 :(得分:6)
您可以使用DecimalFormat,因为它甚至支持区域设置(某些地方使用.
代替,
)
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
String formatted = formatter.format(amount);
答案 2 :(得分:6)
您可以实施TextWatcher
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";
@Override
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);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
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;
}
}
}
要使用它,您可以使用
editText.addTextChangedListener(new NumberTextWatcher(editText));