java - 数字转换成以0开头的字符串
简单写就
String.format("%04d", 3)
不过令我意外的是 StringBuilder + replace 效率居然更高
public class Test {
public static String format2(int shortval) {
String formatted = Integer.toString(shortval);
StringBuilder buf = new StringBuilder("0000");
buf.replace(4 - formatted.length(), 4, formatted);
return buf.toString();
}
public static void main(String[] args) {
String s;
{
long start = System.nanoTime();
int cnt = 100_0000;
while (cnt-- > 0) {
s = String.format("%04d", 3);
}
long end = System.nanoTime();
System.out.println(end - start);
}
{
long start = System.nanoTime();
int cnt = 100_0000;
while (cnt-- > 0) {
s = format2((short) 3);
}
String a ="";
long end = System.nanoTime();
System.out.println(end - start);
}
}
}
疯狂的妞妞 :每一天,做什么都好,不要什么都不做!