问题
I want a thousands separator (,) in EditText when i am typing in editText. after that,i will do some operation on the number.then show the result in the TextView by thousands separator (,).
this is my code:
public class Mainactivity extends Activity {
/** Called when the activity is first created. */
EditText edt;
TextView txt;
Button btn;
OnClickListener myclick = new OnClickListener() {
@Override
public void onClick(View arg0) {
// my calculation
double num1 = Double.parseDouble(edt.getText().toString());
double num2 = num1 + 7;
txt.setText("" + num2);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt = (EditText) findViewById(R.id.edt);
txt = (TextView) findViewById(R.id.txt);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(myclick);
}
}
回答1:
You can use
String value=String.format("%,.2f", num );
to parse the number to String with a thousands separator and then set the result to the TextView or EditText that you want
For example :
txt.setText(String.format("%,.2f", num ));
edt.setText(String.format("%,.2f", num ));
回答2:
Try use this code
@Override
public void afterTextChanged(Editable s) {
try
{
edittext.removeTextChangedListener(this);
String value = edittext.getText().toString();
if (value != null && !value.equals(""))
{
String str = edittext.getText().toString().replaceAll(",", "");
if (value != null && !value.equals(""))
Double.valueOf(str).doubleValue();
edittext.setText(getDecimalFormat(str));
edittext.setSelection(edittext.getText().toString().length());
}
edittex.addTextChangedListener(this);
return;
}
catch (Exception localException)
{
localException.printStackTrace();
edittext.addTextChangedListener(this);
}
}
private String getDecimalFormat(String value)
{
StringTokenizer lst = new StringTokenizer(value, ".");
String str1 = value;
String str2 = "";
if (lst.countTokens() > 1)
{
str1 = lst.nextToken();
str2 = lst.nextToken();
}
String str3 = "";
int i = 0;
int j = -1 + str1.length();
if (str1.charAt( -1 + str1.length()) == '.')
{
j--;
str3 = ".";
}
for (int k = j;; k--)
{
if (k < 0)
{
if (str2.length() > 0)
str3 = str3 + "." + str2;
return str3;
}
if (i == 3)
{
str3 = "," + str3;
i = 0;
}
str3 = str1.charAt(k) + str3;
i++;
}
}
hope help you
来源:https://stackoverflow.com/questions/25823579/edittext-and-textview-formatted-with-thousands-separators-in-android