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

2022-09-01 17:54:40

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

int a=01;

并将其打印为 ?另外,不仅打印,如果我说,也应该将其值打印为.01int b=a;b01


答案 1

我认为这就是你正在寻找的:

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 生成一个字符串,该字符串以特定格式表示数量。


答案 2
// 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)