What API can I use to format an int to be 2 digits long?
For example, in this loop
for (int i = 0; i < 100; i++) {
System.out.println("i is " + i);
}
What can I use to make sure i is printed out like 01, 02, 10, 55 etc (assuming a range of 01-99 )
To be able to print any given number with two zeros after the decimal point, we'll use one more time DecimalFormat class with a predefined pattern: public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#. 00"); return new Double(df.
%02d means an integer, left padded with zeros up to 2 digits.
You could simply do
System.out.printf("i is %02d%n", i);
Have a look at the documentation for Formatter for details. Relevant parts are:
- The format specifiers for general, character, and numeric types have the following syntax:
%[argument_index$][flags][width][.precision]conversion
(In this particular case, you have 0 as flag, 2 as width, and d as conversion.)
Conversion
'd'integral The result is formatted as a decimal integerFlags
'0'The result will be zero-padded
This formatting syntax can be used in a few other places as well, for instance like this:
String str = String.format("i is %02d", i);
String class actually do formatting.
For your case, try:
String.format("%02d",i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With