0

I have edit text with minLength=13. If user enters below 13 characters I want to append the zeros in front of the input to make this length to 13. Ex: user enter 123 -> 0000000000123.

Any approach?

Serafins
  • 1,109
  • 1
  • 16
  • 33
Navinp
  • 23
  • 7

3 Answers3

1

This can be done with String.format, provided the input is an integer:

int input = 123;
int pad_width = 13;
String padded = String.format("%0"+pad_width+"d", input);
// padded is now "0000000000123"

Answers related to this on other questions:

Community
  • 1
  • 1
Kyle Falconer
  • 7,586
  • 5
  • 44
  • 63
0

Yea this is pretty easy. Keep in mind this code is not tested:

// Declaration 
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Declare edittext here
    mEditText = // init code...

}

// Detect when user has pressed done
public void setKeyListener() {
     mEditText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    String s = mEditText.getText().toString();
                    s = appendZerosIfNecessary();
                    return true;
                }
            }
            return false;
        }
    });

// Append if necessary
private String appendZerosIfNecessary(String s) {
    int length = s.length;
    if (s.length < 13) {
        StringBuilder sb = new StringBuilder(s);
        for (int i = length; i < 13; i++) {
            sb.append('0');
        }
        return sb.toString();
    }
    return s;
}

Note this code is not tested, but you get the idea.

EDIT: just reread question you want 0's appended in the beginning.

In this case I would merge the other answer with this one and change appendZerosIfNecessary() to the following:

private String appendZerosIfNecessary(String s) {
   StringBuilder finalString = new StringBuilder();
   for (int i = 0; i < (13 - input.length()); i++){
       finalString.append('0')
   }
   finalString.append(input)
}
AndyRoid
  • 4,754
  • 8
  • 33
  • 70
0

The easiest way would be to check the length of the user's input.

String input = 123;
StringBuilder finalString= new StringBuilder();

for (int i=0; i<13-input.length(); i++){
 finalString.append("0")
}
finalString.append(input)
Serafins
  • 1,109
  • 1
  • 16
  • 33