How do you left pad an int
with zeros when converting to a String
in java?
I\'m basically looking to pad out integers up to 9999
No packages needed:
String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.
Try this one:
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9); // Output: 0009
String a = df.format(99); // Output: 0099
String b = df.format(999); // Output: 0999
Use the class DecimalFormat, like so:
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811));
OUTPUT : 0000811
You need to use a Formatter, following code uses NumberFormat
int inputNo = 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumIntegerDigits(4);
nf.setMinimumIntegerDigits(4);
nf.setGroupingUsed(false);
System.out.println("Formatted Integer : " + nf.format(inputNo));
Output: 0001
int x = 1;
System.out.format("%05d",x);
if you want to print the formatted text directly onto the screen.
Use java.lang.String.format(String,Object...) like this:
String.format("%05d", yournumber);
for zero-padding with a length of 5. For hexadecimal output replace the d
with an x
as in "%05x"
.
The full formatting options are documented as part of java.util.Formatter.