Skip to content

Instantly share code, notes, and snippets.

@ar-android
Last active September 23, 2023 07:57
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ar-android/99358bb39da7fb025bbd to your computer and use it in GitHub Desktop.
Save ar-android/99358bb39da7fb025bbd to your computer and use it in GitHub Desktop.
set currency EditText
private void setCurrency(final EditText edt) {
edt.addTextChangedListener(new TextWatcher() {
private String current = "";
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(current)) {
edt.removeTextChangedListener(this);
Locale local = new Locale("id", "id");
String replaceable = String.format("[Rp,.\\s]",
NumberFormat.getCurrencyInstance().getCurrency()
.getSymbol(local));
String cleanString = s.toString().replaceAll(replaceable,
"");
double parsed;
try {
parsed = Double.parseDouble(cleanString);
} catch (NumberFormatException e) {
parsed = 0.00;
}
NumberFormat formatter = NumberFormat
.getCurrencyInstance(local);
formatter.setMaximumFractionDigits(0);
formatter.setParseIntegerOnly(true);
String formatted = formatter.format((parsed));
String replace = String.format("[Rp\\s]",
NumberFormat.getCurrencyInstance().getCurrency()
.getSymbol(local));
String clean = formatted.replaceAll(replace, "");
current = formatted;
edt.setText(clean);
edt.setSelection(clean.length());
edt.addTextChangedListener(this);
}
}
});
}
@nmluthfi
Copy link

makasih mas kode nya :)

@afirdausw
Copy link

sangat membantu, terima kasih dev

@andresual
Copy link

worksssss, makasih bro!

@gandalivs
Copy link

edit and work, thx

@herufredi85
Copy link

tq kawan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment