I want to add 3 decimal places currency formatting to EditText using TextWatcher at the beginning, value is 0.000 and the number should change right to left
eg: if I pressed 1,2,3,4,5 in order value should appear as this 12.345
following code is worked only for 2 decimal places. Please anyone helps me how to change this code for 3 decimal places or another solution
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
Context context;
public CurrencyTextWatcher() {
mEditing = false;
}
public synchronized void afterTextChanged(Editable s) {
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
try{
String formatted = nf.format(Double.parseDouble(digits)/100);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void onTextChanged(CharSequence s, int start, int before, int count) { }
}
Divide 1000 instead of 100 and also setMinimumFractionDigits
for NumberFormat
as 3.
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
Context context;
public CurrencyTextWatcher() {
mEditing = false;
}
public synchronized void afterTextChanged(Editable s) {
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(3);
try{
String formatted = nf.format(Double.parseDouble(digits)/1000);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void onTextChanged(CharSequence s, int start, int before, int count) { }
}