Add leading zeroes to number in Java?
To add leading zeroes to a number in Java, you can use the format
method of the String
class, along with a format string that specifies the desired length and padding character.
For example, to add leading zeroes to a number such that the resulting string is always 6 characters long, you can use the following code:
int number = 123;
String result = String.format("%06d", number); // result is "000123"
The format string "%06d"
specifies that the number should be formatted as a decimal integer (d
) and padded with zeroes (0
) on the left to a minimum width of 6 characters.
You can also use the printf
method of the PrintStream
class to achieve the same result:
int number = 123;
String result = String.format("%06d", number); // result is "000123"
Keep in mind that these methods only work for numerical types such as int
, long
, and float
. If you want to pad a string with leading zeroes, you can use a similar format string and pass the string as the argument:
String str = "abc";
String result = String.format("%06s", str); // result is "000abc"
This will pad the string with zeroes on the left to a minimum width of 6 characters. If the string is already longer than the specified width, it will not be truncated.