How to Pad an Integer With Zeros on the Left

How can I pad an integer with zeros on the left?

Use java.lang.String.format(String,Object...) like this:

String.format("%05d", yournumber);

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

The full formatting options are documented as part of java.util.Formatter.

How to left pad an integer with 0's (zeros)?

By default, white spaces are used for padding, you should add 0 to the format specifier to make the padding character 0s.

printf("%04d",number);

Left padding a String with Zeros

If your string contains numbers only, you can make it an integer and then do padding:

String.format("%010d", Integer.parseInt(mystring));

If not I would like to know how it can be done.

How to pad integer printing with leading zeros?

tostring[0]=(char)0; does not write the character representation of 0 into tostring[0]. It writes a zero. You want tostring[0] = '0', with single quotes. And similarly, to write the character representation of a single digit, you can write tostring[1] = '0' + hours (If hours is 5, then '0' + 5 is the character value used to represent 5 in the local character set. Thankfully, it was standardized long ago that those representations should be sequential so that sort of thing works.) But, unless the point of this exercise is to avoid using printf, you should really just use printf.

Padding integer with zeros

You can use the built-in function PadLeft:

int i = 5;
var result = i.ToString().PadLeft(8, '0');

Note: this doesn't work for negative numbers (you'd get 00000000-5).

For that you can use the built-in formatters:

int i = 5;
var result = string.Format("{0:D8}", i);

Left zero padded format numbers

Try %04d instead:

  • 0 indicates what you're using to pad;
  • 4 is the width of the number (you had 5 before);
  • d represents an integer (incl. byte, short, int, long, bigint).
String.format("%04d", Integer.parseInt(something));

Left padding an integer with zero (Java)

How about this:

String.format("%010d", 123456);

Details: Formatter

or

org.apache.commons.lang.StringUtils.leftPad("123456", 10, "0");

Details: StringUtils



Related Topics



Leave a reply



Submit