如何在Java中写一个两位数的整数?例如,如果整数小于 10,则程序应01返回09. 我需要0在一位数字前面。类似于%.2f 双类型的东西。
34392 次
3 回答
21
假设,既然你知道%.2ffor 格式化double,那么你至少知道formatting.
因此,要适当地格式化您的整数,您可以在开头添加一个0before%2d来填充您的数字:-0
int i = 9;
System.out.format("%02d\n", i); // Will print 09
于 2012-10-22T10:44:55.993 回答
16
使用String.format方法...
例子
System.out.println(String.format("%02d", 5));
System.out.println(String.format("%02d", 55));
System.out.println(String.format("%02d", 15));
于 2012-10-22T10:50:15.883 回答