Search code examples
androidandroid-edittextdecimalformatandroid-textwatcher

Different behavior with diffrent device in DecimalFormat


I have an EditText that converts user input, for example, 1000000 to 1,000,000. this is the code I use as a converter:

private TextWatcher onTextChangedListener(final EditText editText) {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

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

            }

            @Override
            public void afterTextChanged(Editable s) {
                editText.removeTextChangedListener(this);

                try {
                    String originalString = s.toString();

                    Long longval;
                    if (originalString.contains(",")) {
                        originalString = originalString.replaceAll(",", "");
                    }
                    longval = Long.parseLong(originalString);

                    DecimalFormat formatter = new DecimalFormat("###,###,###");
                    String formattedString = formatter.format(longval);

                    //setting text after format to EditText
                    editText.setText(formattedString);
                    editText.setSelection(editText.getText().length());
                } catch (NumberFormatException nfe) {
                    nfe.printStackTrace();
                }

                editText.addTextChangedListener(this);
            }
        };
    }

When I tried it on the emulator (both API 25 and 29), it behaves correctly, the EditText I type in the right format (1,000,000) but when I release the application, people are reporting that the format has become 1.000000 and then when the function around EditText is used, the app crashes, the store crash report says it's a NumberFormatException. What can possibly cause this and how do I work around it?


Solution

  • Turned out to be locale problem, that code I used there provide no locale setting which results in a different format if another device is using different locale. So I implement this code:

    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
    DecimalFormat formatter = new DecimalFormat("###,###,###", symbols);
    

    And it works fine with a device with a different locale