21

I want to add some leading zeroes to a string, the total length must be eight characters. For example:

123 should be 00000123
1243 should be 00001234
123456 should be 00123456
12345678 should be 12345678

What's the easiest way?

Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
tertest
  • 260
  • 1
  • 3
  • 6

6 Answers6

36

A cheesy little trick

String str = "123";
String formatted = ("00000000" + str).substring(str.length())

If you started with a number instead:

Int number = 123;
String formatted = String.format("%08d", number);
Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79
  • 2
    the cheesy little trick is worth remembering for lots of different languages - sql dialects you don't use often for example – Levin Magruder Nov 26 '13 at 18:09
  • 1
    The first example is nice at first but it breaks if the original number is longer than 8 digits. Furthermore, if you do `("00000000" + number)` with number being an integer or long it will provide you with a string as a result. But the second option will be safer. – pablisco Aug 13 '14 at 09:54
30

Use String.format(), it has a specifier for that already:

String.format("%08d", myInteger);

More generally, see the javadoc for Formatter. It has a lot of neat stuff -- more than you can see at a first glance.

fge
  • 119,121
  • 33
  • 254
  • 329
10

Using apache common langs lib:

StringUtils.leftPad(str, 8, '0');
Andrey Sarul
  • 1,382
  • 2
  • 16
  • 20
7

Using DecimalFormat:

static public void main(String[] args) {
    int vals[] = {123, 1243, 123456, 12345678};
    DecimalFormat decimalFormat = new DecimalFormat("00000000");
    for (int val : vals) {
        System.out.println(decimalFormat.format(val));
    }
}

Output:

00000123
00001243
00123456
12345678
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
4

Why not make a simple padding function? I know there are libraries, but this is a very simple task.

System.out.println(padStr(123, "0", 8));
System.out.println(padStr(1234, "0", 8));
System.out.println(padStr(123456, "0", 8));
System.out.println(padStr(12345678, "0", 8));       

public String padStr(int val, String pad, int len) {
  String str = Integer.toString(val);
  while (str.length() < len)
    str = pad + str;
  return str;
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1
public static void main(String[] args)
{
    String stringForTest = "123";
    int requiredLengthAfterPadding = 8;
    int inputStringLengh = stringForTest.length();
    int diff = requiredLengthAfterPadding - inputStringLengh;
    if (inputStringLengh < requiredLengthAfterPadding)
    {
        stringForTest = new String(new char[diff]).replace("\0", "0")+ stringForTest;
    }
    System.out.println(stringForTest);
}
Fathah Rehman P
  • 8,401
  • 4
  • 40
  • 42