开发者

Format an int with zero padding in Java

开发者 https://www.devze.com 2023-01-18 03:23 出处:网络
How do I 开发者_Go百科get the following assertion to succeed? { int i = 5; assertEquals(\"005\", String.format(\"%1??s\", i));

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

精彩评论

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