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
with leading zeros (e.g. 1 = 0001
).
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
with leading zeros (e.g. 1 = 0001
).
Try this one:
The only problem with this approach is that it makes you put on your thinking hat to figure out how it works.
Check my code that will work for integer and String.
Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code
Use the class DecimalFormat, like so:
OUTPUT : 0000811
No packages needed:
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.
Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.