tags:

views:

57

answers:

1

How do I get the following assertion to succeed?

{
  int i = 5;
  assertEquals("005", String.format("%1??s", i));
}

Problem: I need to format an int as a string of equal length.

+1  A: 

How about:

assertEquals("005", String.format("%03d", i));

Adding a leading zero to the width of the format says that you want the field left-padded with zeroes.

From the docs under 'Number Localization Algorithm', pt. 4.:

If the '0' flag is given, then the locale-specific zero digits are inserted after the sign character, if any, and before the first non-zero digit, until the length of the string is equal to the requested field width.

martin clayton
Thanks alot, works great