I need to format input currency with 2 decimal format example when user enter 2 it looks $2.00 then when when user enter 2 it convert to $22.00 ... etc
I approach to something similar , when user enter 2 it convert to $0.02 next 2 will be like this $0.22
any one can help me thank you
public class MoneyTextWatcher implements TextWatcher {
private final WeakReference<EditText> editTextWeakReference;
public MoneyTextWatcher(EditText mEditText) {
editTextWeakReference = new WeakReference<EditText>(mEditText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
EditText editTex = editTextWeakReference.get();
if(!s.toString().equals(editTex.getText())) {
editTex.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[$,.]", "");
double parsed = Double.parseDouble(cleanString.replaceAll("[^\\d]", ""));
String formatted = NumberFormat.getCurrencyInstance().format((parsed / 100));
editTex.setText(formatted);
editTex.setSelection(formatted.length());
editTex.addTextChangedListener(this);
}
@Override
public void afterTextChanged(Editable s) {
}
}
}
Keep the number entered by the user stored apart, since if you use your edittext.text you will have more problems.
Then use DecimalFormat to format it like you need.
For the first, maybe its a good way to restore the original input to the edittext as soon as the users begins editing, this way you can avoid problems with the editing.
Hope this helps.
I think you can try the following:
Layout:
Activity:
with text watcher as the following:
HI below code will convert every number to two decimal. the value should be number, characters and special characters can cause numberformat exception. please handle that as you needed. Thanks