johnnyhill johnnyhill - 4 years ago 270
Android Question

Android edit text decimal format

Can I ask how to format string value e.g.

? Apparently I'm doing currency related stuff for android application, I can managed to just format string value
without the dot separator in the edit text. I would like to store the string value for later to be used to parseDouble so that I will need to calculate and have some decimals. I managed to do with just comma separator but any idea on how to make the dot to be shown in the edit text as well?
The following is my code:

amountText.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

public void onTextChanged(CharSequence s, int start, int before, int count) {

public void afterTextChanged(Editable s) {
try {
String editText = amountText.getText().toString();
String newStr = editText.replace("$", "").replace(",", "");
String formattedString = formatString(customer.getProperty().get(groupPosition).getAmount());
// to place the cursor at the end of text
} catch (NumberFormatException nfe) {
} catch (Exception e) {

public String formatString(String s)
String givenstring = s.toString();
Long longval;
if (givenstring.contains(",")) {
givenstring = givenstring.replaceAll(",", "");
longval = Long.parseLong(givenstring);
DecimalFormat formatter = new DecimalFormat("#,###,###");
String formattedString = formatter.format(longval);
return formattedString;

I have tested use parseDouble but when I input "." in
, it just won't appear, and if I used long variable instead, it will give wrong format and error. (java.lang.NumberFormatException: Invalid long: "500000.00"). All values are done in string and later processing I will just parse the value when doing calculation.
Thank you and appreciate for anyone guidance and I apologize if there exists the post that is similar as I did not manage to find solution yet.

Answer Source

Try this:

public void afterTextChanged(Editable view) {
    String s = null;
    try {
        // The comma in the format specifier does the trick
        s = String.format("%,d", Long.parseLong(view.toString()));
    } catch (NumberFormatException e) {
    // Set s back to the view after temporarily removing the text change listener

Source: How to Automatically add thousand separators as number is input in EditText

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download