8

I have several strings of different length

"2323" "245" "353352" 

I need to convert them to string of the same size such as:

"0002323" "0000245" "0353352" 

How can I automatically add the correct number of 0s in front of each string ?

thanks

2
  • What should happen if the input string is longer than the expected output format? Commented Mar 23, 2011 at 9:21
  • you can also count the number of characters/digits in a string and then just append the desired number of values to the front which could be 0 or space or any other character. Commented Nov 15, 2013 at 18:55

3 Answers 3

17

Use String.format:

Integer i = Integer.valueOf(src); String format = "%1$07d"; String result = String.format(format, i); 
Sign up to request clarification or add additional context in comments.

1 Comment

uhm ok. However src in my case is already a string and not an integer. Should I convert string > int > string ?
5

Using DecimalFormat, String.format, or printf you can format a Number.

Example using DecimalFormat:

NumberFormat formatter = new DecimalFormat("0000000"); String number = formatter.format(2500); 

Hope it helps.

Regards!

Comments

4

Or use Apache Commons / Lang:

String s = "245"; String zeroPadded = StringUtils.leftPad(s, 6, '0'); 

Reference:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.