Java – which API can I use to format ints as 2 digits?
•
Java
What API can I use to format ints as 2-digit numbers?
For example, in this loop
for (int i = 0; i < 100; i++) { System.out.println("i is " + i); }
What can I use to ensure that I print out things like 01, 02, 10, 55, etc. (assuming the range of 01-99)
Solution
You can do it simply
System.out.printf("i is %02d%n",i);
For more information, check the formatter's documentation Relevant parts include:
(in this special case, your mark is 0, the width is 2, and it is converted to d)
This formatting syntax can also be used in several other places, such as:
String str = String.format("i is %02d",i);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码