【发布时间】:2011-02-11 21:39:57
【问题描述】:
我有一个整数 100,如何将其格式化为类似于 00000100(总是 8 位长)?
【问题讨论】:
-
'8 digits'(而不是'8 numbers')会更正确
我有一个整数 100,如何将其格式化为类似于 00000100(总是 8 位长)?
【问题讨论】:
如果 Google Guava 是一个选项:
String output = Strings.padStart("" + 100, 8, '0');
或者 Apache Commons Lang:
String output = StringUtils.leftPad("" + 100, 8, "0");
【讨论】:
另一种方式。 ;)
int x = ...
String text = (""+(500000000 + x)).substring(1);
-1 => 99999999(九进制补码)
import java.util.concurrent.Callable;
/* Prints.
String.format("%08d"): Time per call 3822
(""+(500000000+x)).substring(1): Time per call 593
Space holder: Time per call 730
*/
public class StringTimer {
public static void time(String description, Callable<String> test) {
try {
// warmup
for(int i=0;i<10*1000;i++)
test.call();
long start = System.nanoTime();
for(int i=0;i<100*1000;i++)
test.call();
long time = System.nanoTime() - start;
System.out.printf("%s: Time per call %d%n", description, time/100/1000);
} catch (Exception e) {
System.out.println(description+" failed");
e.printStackTrace();
}
}
public static void main(String... args) {
time("String.format(\"%08d\")", new Callable<String>() {
int i =0;
public String call() throws Exception {
return String.format("%08d", i++);
}
});
time("(\"\"+(500000000+x)).substring(1)", new Callable<String>() {
int i =0;
public String call() throws Exception {
return (""+(500000000+(i++))).substring(1);
}
});
time("Space holder", new Callable<String>() {
int i =0;
public String call() throws Exception {
String spaceHolder = "00000000";
String intString = String.valueOf(i++);
return spaceHolder.substring(intString.length()).concat(intString);
}
});
}
}
【讨论】:
如果您只需要打印出来,这是一个较短的版本:
System.out.printf("%08d\n", number);
【讨论】:
如果你需要解析这个字符串或者支持 i18n 考虑扩展
java.text.Format
对象。使用其他答案来帮助您获得格式。
【讨论】:
这也有效:
int i = 53;
String spaceHolder = "00000000";
String intString = String.valueOf(i);
String string = spaceHolder.substring(intString.lenght()).contract(intString);
但其他示例要容易得多。
【讨论】:
String.format 使用 格式字符串,描述为 here
【讨论】:
你也可以使用DecimalFormat这个类,像这样:
NumberFormat formatter = new DecimalFormat("00000000");
System.out.println(formatter.format(100)); // 00000100
【讨论】:
试试这个:
String formattedNumber = String.format("%08d", number);
【讨论】: