Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading zeroes to a string [duplicate]

Tags:

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?

like image 914
user2425743 Avatar asked Jun 13 '13 22:06

user2425743


People also ask

How do you add a leading zero to a string?

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.

How do you add a leading zero to a double in Java?

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.

How do you add leading zeros to a string in Python?

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.

How can I pad a value with leading zeros?

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.


2 Answers

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.

like image 22
fge Avatar answered Sep 28 '22 04:09

fge


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);
like image 126
Jean-Bernard Pellerin Avatar answered Sep 28 '22 06:09

Jean-Bernard Pellerin