I have an integer 100
, how do I format it to look like 00000100
(always 8 digits long)?
You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
One way to do this is with string format codes. For example, if you want to pad a string to a certain length with spaces, use something like this: String padded = String. format("%-20s", str);
There are two main ways to add zeros at the start of an integer number in Java, first by using format() method of String class, and second by using format() method of DecimalFormat class. String.
Try this:
String formattedNumber = String.format("%08d", number);
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