Reputation: 23
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?
Upvotes: 0
Views: 479
Reputation: 8490
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:
Upvotes: 1
Reputation: 5057
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)
}
Upvotes: 0
Reputation: 1247
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)
Upvotes: 0