简体   繁体   中英

Format an int with zero padding in Java

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM