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?
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
To add leading zeros to a number, you need to format the output. Let's say we need to add 4 leading zeros to the following number with 3 digits. int val = 290; For adding 4 leading zeros above, we will use %07d i.e. 4+3 = 7.
For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.
To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With