Reputation: 1598
All- I have been struggling with this for a while and have looked at all the other questions about this sort of thing but I just can't figure it out: I have an edttext field that needs to be formatted for currency. I have tried the code in all of the other questions relating to this but no matter what I try it just doesn't work. Here is my code:
EditText text = (EditText)findViewById(R.id.edit_bill);
text.setRawInputType(Configuration.KEYBOARD_12KEY);
text.addTextChangedListener(new TextWatcher(){
EditText text = (EditText)findViewById(R.id.edit_bill);
DecimalFormat dec = new DecimalFormat("0.00");
public void afterTextChanged(Editable arg0) {
}
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().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
{
String userInput= ""+s.toString().replaceAll("[^\\d]", "");
if (userInput.length() > 0) {
Float in=Float.parseFloat(userInput);
float percen = in/100;
text.setText("$"+dec.format(percen));
text.setSelection(text.getText().length());
}
}
}
});
This code is inside of an onClick method. Does that make a difference (eg. the text will only be formatted when the user clicks the button)?. Thanks in advance!
Upvotes: 1
Views: 1179
Reputation: 46856
I have used this method in the past for formatting money.
static public String customFormat(String pattern, double s ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String stringFormatOutput = myFormatter.format(s);
return stringFormatOutput;
}
it can be used like this:
String strPrice = customFormat("$###,##0.00", 300.2568);
mTxt.setText(strPrice);
just change the "300.2568" to be your price. This probably could work just as well for floats instead of doubles.
Upvotes: 2