在Java中的变量中以两位数格式保存整数

Mis*_*u4u 22 java numbers

如何在Java中以两位数格式存储整数?我可以设置

int a=01;
Run Code Online (Sandbox Code Playgroud)

并将其打印为01?此外,如果我说的话int b=a;,不仅打印b也应该打印它的价值01.

tre*_*123 73

我想这就是你要找的东西:

int a = 1;
DecimalFormat formatter = new DecimalFormat("00");
String aFormatted = formatter.format(a);

System.out.println(aFormatted);
Run Code Online (Sandbox Code Playgroud)

或者,更简单地说:

int a = 1;
System.out.println(new DecimalFormat("00").format(a));
Run Code Online (Sandbox Code Playgroud)

int只存储一个数量,01和1表示相同的数量,因此它们以相同的方式存储.

DecimalFormat构建一个String,表示特定格式的数量.


Jos*_*ani 13

// 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)
Run Code Online (Sandbox Code Playgroud)

  • 应该是"%02d"而不是"%2d" (2认同)

Chr*_*ach 6

这是不可能的,因为整数是整数.但是如果需要,可以格式化整数(DecimalFormat).


mbp*_*tel 5

看看下面的格式,上面的格式对我来说不起作用

String.format(“%02d”,myNumber)