开发者

Format an int with zero padding in Java

How do I 开发者_Go百科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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜