【发布时间】:2012-10-12 03:52:55
【问题描述】:
可能重复:
How to format a number 0..9 to display with 2 digits (it’s NOT a date)
如何在 Java 中写出一个两位数的整数?例如,如果整数小于 10,则程序应将 01 返回到 09。我需要在一位数字前面加上0。类似于 %.2f 的双精度类型。
【问题讨论】:
可能重复:
How to format a number 0..9 to display with 2 digits (it’s NOT a date)
如何在 Java 中写出一个两位数的整数?例如,如果整数小于 10,则程序应将 01 返回到 09。我需要在一位数字前面加上0。类似于 %.2f 的双精度类型。
【问题讨论】:
假设,既然您知道%.2f 用于格式化double,那么您至少知道formatting。
因此,为了适当地格式化您的整数,您可以在 %2d 之前添加一个 0 以在开头使用 0 填充您的数字:-
int i = 9;
System.out.format("%02d\n", i); // Will print 09
【讨论】:
使用 String.format 方法...
例子
System.out.println(String.format("%02d", 5));
System.out.println(String.format("%02d", 55));
System.out.println(String.format("%02d", 15));
【讨论】: