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?
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?
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);
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.
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
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;
}
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);
}