你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
你如何在java中转换为字符串时留下一个零填充int ?
我基本上是在寻找以前导零填充到9999的整数(例如1 = 0001)。
当前回答
下面是如何不使用DecimalFormat格式化字符串的方法。
字符串。格式(“% 2 d”,9)
09
字符串。格式(“% d 03”,19)
019
字符串。格式(“% 04 d”,119年)
0119
其他回答
如果性能在您的情况下很重要,您可以自己做,与String相比开销更少。格式功能:
/**
* @param in The integer value
* @param fill The number of digits to fill
* @return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
性能
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
结果
自带功能:1697ms
字符串。格式:38134毫秒
int x = 1;
System.out.format("%05d",x);
如果您想将格式化的文本直接打印到屏幕上。
不需要软件包:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
这将把字符串填充到三个字符,并且很容易为四个或五个字符添加更多的部分。我知道这在任何方面都不是完美的解决方案(特别是如果你想要一个大的填充字符串),但我喜欢它。
Kotlin的
fun Calendar.getFullDate(): String {
val mYear = "${this.get(Calendar.YEAR)}-"
val mMonth = if (this.get(Calendar.MONTH) + 1 < 10) {
"0${this.get(Calendar.MONTH) + 1}-"
} else {
"${this.get(Calendar.MONTH)+ 1}-"
}
val mDate = if (this.get(Calendar.DAY_OF_MONTH) < 10) {
"0${this.get(Calendar.DAY_OF_MONTH)}"
} else {
"${this.get(Calendar.DAY_OF_MONTH)}"
}
return mYear + mMonth + mDate
}
并将其用作
val date: String = calendar.getFullDate()
假设你想把11打印成011
您可以使用格式化程序:“%03d”。
你可以像这样使用这个格式化器:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
另外,一些java方法直接支持这些格式化器:
System.out.printf("%03d", a);