%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
In your example, it is a placeholder character. It means when % is encountered, the next character determines how to interpret the argument and insert it into the printed result. %s means interpret as string, %d is for digit, %x is digit in hexadecimal, %f is for float, etc....
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
%s in the format string is replaced with the content of language . %s is a format specifier. Similarly, %x is replaced with the hexadecimal value of number in String. format("Number: %x", number) .
String.format("%03d", 1) // => "001"
// │││ └── print the number one
// ││└────── ... as a decimal integer
// │└─────── ... minimum of 3 characters wide
// └──────── ... pad with zeroes instead of spaces
See java.util.Formatter
for more information.
Use %03d
in the format specifier for the integer. The 0
means that the number will be zero-filled if it is less than three (in this case) digits.
See the Formatter
docs for other modifiers.
If you are using a third party library called apache commons-lang, the following solution can be useful:
Use StringUtils
class of apache commons-lang :
int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
As StringUtils.leftPad()
is faster than String.format()
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