gpt4 book ai didi

java - 想在java中格式化大于20位的数字吗?

转载 作者:行者123 更新时间:2023-12-01 11:26:53 25 4
gpt4 key购买 nike

我想在 Android 中使用逗号格式化大于 20 位的数字。我在 EditText 上使用了 DecimalFormat 类和 TextWatcher 但问题是当我输入大于 20 位的数字时,它会在 20 位数字后显示 0,而不是数量。
直到 20 位数字都可以正常工作。
任何帮助都值得赞赏。提前致谢

private 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;
}
}

}

最佳答案

使用BigDecimalWhen/why should we use BigDecimal?

    String number = "12345678910111213141516000";
BigDecimal bd = new BigDecimal(number);
DecimalFormat formatter = new DecimalFormat("#,###,###,###.#####");
System.out.println("You want it : " + formatter.format(bd));

Number num = formatter.parse(number);
System.out.println("You don't want it : " + formatter.format(num));

输出

You want it : 12,345,678,910,111,213,141,516,000
You don't want it : 12,345,678,910,111,213,000,000,000

关于java - 想在java中格式化大于20位的数字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751134/

25 4 0
文章推荐: java - 在 Java 中从 List 创建 JSON 数组