reproduced from: http://ych0108.iteye.com/blog/2174134 p>
Java int String number is not enough to fill in the front zero
String.format("%010d", 25); //25为int型
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("0").append(str);//左补0
// 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.
So,
, and I recently did a search on string.format, which actually comes with its own way to fill in the zero,
String.format("%06",12);//其中0表示补零而不是补空格,6表示至少6位
div>