aneuryzm
aneuryzm

Reputation: 64874

How to format numbers to same number of digits, 0-padded?

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

Upvotes: 8

Views: 11105

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299218

Or use Apache Commons / Lang:

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

Reference:

Upvotes: 4

redent84
redent84

Reputation: 19249

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!

Upvotes: 5

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

Use String.format:

Integer i = Integer.valueOf(src);
String format = "%1$07d";
String result = String.format(format, i);

Upvotes: 17

Related Questions