如何在Java中以两位数格式存储整数?我也可以设置
int a=01;
并将其打印为01
?此外,不仅打印,如果我说int b=a;
,b
也应将其值打印为01
。
答案 0 :(得分:59)
我认为这就是你要找的东西:
int a = 1;
DecimalFormat formatter = new DecimalFormat("00");
String aFormatted = formatter.format(a);
System.out.println(aFormatted);
或者,更简单地说:
int a = 1;
System.out.println(new DecimalFormat("00").format(a));
int只存储一个数量,01和1表示相同的数量,因此它们以相同的方式存储。
DecimalFormat构建一个String,表示特定格式的数量。
答案 1 :(得分:12)
// below, %02d says to java that I want my integer to be formatted as a 2 digit representation
String temp = String.format("%02d", yourIntValue);
// and if you want to do the reverse
int i = Integer.parse(temp);
// 2 -> 02 (for example)
答案 2 :(得分:6)
这是不可能的,因为整数是整数。但是如果需要,可以格式化整数(DecimalFormat)。