问题
In Android is there an easy way to insert commas into a numberical value? ie if I have an EditText with 12345 in it, how can I display this as 12,345?
I think I can do it using substring and chopping it up into x number of 3 number chunks then concatenating the answer with ',' between each 3 number chunk. This would be pretty easy if length of number was constant, but as the number could be from one digit to, say 20, it makes it more complex.
Just curious if there is a simple and clean way to achieve this before I go about making my substring solution.
Cheers
回答1:
If Java --
Use something like this:
double amount = 2324343192.015;
NumberFormat formatter = new DecimalFormat("###,###,###.##");
System.out.println("The Decimal Value is: "+formatter.format(amount));
Result: The Decimal Value is: 2,324,343,192.02
回答2:
you can first declare below class:
public class MyNumberWatcher implements TextWatcher {
private EditText editText;
public MyNumberWatcher(EditText editText) {
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
editText.removeTextChangedListener(this);
String sEditText = editText.getText().toString();
sEditText = sEditText.replace(",", "");
if (sEditText.length() > 0) {
DecimalFormat sdd = new DecimalFormat("#,###");
Double doubleNumber = Double.parseDouble(sEditText);
String format = sdd.format(doubleNumber);
editText.setText(format);
editText.setSelection(format.length());
}
editText.addTextChangedListener(this);
}
}
then in xml file:
<EditText
android:id="@+id/txt"
style="@style/edit_text_style"
android:inputType="number"/>
and in main activity:
TextView txt = findViewById(R.id.txt);
txt.addTextChangedListener(new MyNumberWatcher(txt));
来源:https://stackoverflow.com/questions/4220167/inserting-commas-into-integers