[英]Save an integer in two digit format in a variable in Java
How can I store an integer in two digit format in Java?如何在Java中以两位数格式存储整数? Like can I set
喜欢我可以设置
int a=01;
and print it as 01
?并将其打印为
01
? Also, not only printing, if I say int b=a;
此外,不仅打印,如果我说
int b=a;
, b
should also print its value as 01
. ,
b
还应将其值打印为01
。
I think this is what you're looking for:我认为这就是你要找的:
int a = 1;
DecimalFormat formatter = new DecimalFormat("00");
String aFormatted = formatter.format(a);
System.out.println(aFormatted);
Or, more briefly:或者,更简单地说:
int a = 1;
System.out.println(new DecimalFormat("00").format(a));
An int just stores a quantity, and 01 and 1 represent the same quantity so they're stored the same way. int 只存储一个数量,而 01 和 1 代表相同的数量,因此它们的存储方式相同。
DecimalFormat builds a String that represents the quantity in a particular format. DecimalFormat构建一个以特定格式表示数量的字符串。
// 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)
This is not possible, because an integer is an integer.这是不可能的,因为整数就是整数。 But you can format the Integer, if you want ( DecimalFormat ).
但是如果需要,您可以格式化整数( DecimalFormat )。
look at the below format its work above format can work for me看看下面的格式它的工作上面的格式可以为我工作
System.out.printf("%02d", myNumber) System.out.printf("%02d", myNumber)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.