0

I want to prepend zeros to an int if its string equivalent length is less than 6. Similar to String.format. Example:

int e = 21;
System.out.println(String.format("%06d", e)); //000021
int e = 3564;
System.out.println(String.format("%06d", e)); //003564

What I need is for the above inputs 210000 and 356400 the zeros prepended at the end. Is there something already implemented which will do the job or do i need to code it by my self? If so how to deal with variable length?

The Head Rush
  • 2,522
  • 2
  • 21
  • 39
Trillian
  • 351
  • 2
  • 12

4 Answers4

4
while (e < 100_000) e *= 10;

Self-explanatory. I don't think there is an easier way than that.

Edit: Since e can be 0, I'd wrap the above statement into a function:

public static String pad(int input) {
  if (input == 0) return "000000";
  while (input < 100_000) input *= 10;
  return "" + input;
}
Silviu Burcea
  • 4,573
  • 1
  • 24
  • 41
4

If wanted to do something like what Dimitri suggests, but you don't want to depend on an external library, you write a little method:

StringBuilder sb = new StringBuilder(6);
sb.append(e);
sb.append("000000", Math.min(sb.length(), 6), 6);
return sb.toString();
Andy Turner
  • 122,430
  • 10
  • 138
  • 216
1

If you can use StringUtils, you have access to the rightPad method :

StringUtils.rightPad(String.valueOf(e), 6, "0");
Dimitri Mockelyn
  • 1,505
  • 2
  • 11
  • 17
1

The following method pads the supplied string, with the supplied character, until the field width is reached.

   public static String rightPad(String str, int fieldwidth, char c) {
      StringBuilder sb = new StringBuilder(str);
      while (fieldwidth > sb.length()) {
         sb.append(c);
      }
      return sb.toString();
   }

Example: To pad 1234 with two zeros, do the following:

int v = 1234;
String padded = rightPad(Integer.toString(v), 6, '0');

WJS
  • 22,083
  • 3
  • 14
  • 32