Skip to main content
  1. About
  2. For Teams
Asked
Viewed 11k times
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?
    user
    –  user
    2011-03-23 09:21:49 +00:00
    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.
    AquaAlex
    –  AquaAlex
    2013-11-15 18:55:13 +00:00
    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

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.