Last active
September 23, 2023 07:57
-
-
Save ar-android/99358bb39da7fb025bbd to your computer and use it in GitHub Desktop.
set currency EditText
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
edit and work, thx