In Java, int is converted to string, and zero is added before the number of bits is insufficient

reproduced from:

Java int String number is not enough to fill in the front zero

String.format("%010d", 25); //25int

0 represents the character to be filled before
10 represents the length of the string
and d represents the argument of integer type

today I want to put an int to String not enough digits in front of the zero, in the original to see if there is a ready-made API, the results found most of the following

public static String addZeroForNum(String str,int strLength) {  
  int strLen =str.length();  
  if (strLen <strLength) {  
   while (strLen< strLength) {  
    StringBuffersb = new StringBuffer();  
//    sb.append(str).append("0");//右补0  
    str= sb.toString();  
    strLen= str.length();  

  return str;  

but I think it’s a little bit of a hassle, so I thought of a slightly easier way to do it, the following line would be

String str = String.format("%5d", num).replace(" ", "0");  

, where num is an int and STR is the converted result. That’s easy.


, and I recently did a search on string.format, which actually comes with its own way to fill in the zero,


Read More: