Skip to content

Instantly share code, notes, and snippets.

@mohosyny
Created April 3, 2022 05:19
Show Gist options
  • Select an option

  • Save mohosyny/2aae1978115f0453876874de95cf3004 to your computer and use it in GitHub Desktop.

Select an option

Save mohosyny/2aae1978115f0453876874de95cf3004 to your computer and use it in GitHub Desktop.
public class ThreeDigitDecimalFormatWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private EditText et;
public ThreeDigitDecimalFormatWatcher(EditText et) {
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.US);
df = new DecimalFormat("#,###.##", decimalFormatSymbols);
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###", decimalFormatSymbols);
this.et = et;
hasFractionalPart = false;
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
hasFractionalPart = s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
// Number n = df.parse(v);
BigDecimal n = new BigDecimal(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
}
et.addTextChangedListener(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment