I'm using a class to format the value of my EditText to currency. This class use the function NumberFormat.getCurrencyInstance().format((parsed/100)); to format. This class make my value with two decmal places (R$2,00). I want it to have three decimal places (R$2,000). Its for gas value. Here in Brasil we use three decimal places for gas.
This is the class I'm using:
public class MascaraMonetaria implements TextWatcher{
final EditText mEditText;
String current;
static Context context;
public MascaraMonetaria(EditText mEditText, String current, Context context) {
super();
this.mEditText = mEditText;
this.current = current;
}
@Override
public void afterTextChanged(Editable arg0) {}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
if (!s.toString().equals(current)) {
mEditText.removeTextChangedListener(this);
String cleanString = s.toString().replaceAll("[R$,.]", "");
double parsed = Double.parseDouble(cleanString);
String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));
current = formatted;
mEditText.setText(formatted);
mEditText.setSelection(formatted.length());
mEditText.addTextChangedListener(this);
}
}
public static double stringMonetarioToDouble(String str) {
double retorno = 0;
try {
boolean hasMask = ((str.indexOf("R$") > -1 || str.indexOf("$") > -1) && (str
.indexOf(".") > -1 || str.indexOf(",") > -1));
// Verificamos se existe máscara
if (hasMask) {
// Retiramos a mascara.
str = str.replaceAll("[R$]", "").replaceAll("[$]", "").replaceAll("[.]", "").replaceAll("[,]", ".");
}
// Transformamos o número que está escrito no EditText em double.
retorno = Double.parseDouble(str);
} catch (NumberFormatException e) {
}
return retorno;
}
}