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
).
Let's say you want to print
11
as011
You could use a formatter:
"%03d"
.You can use this formatter like this:
Alternatively, some java methods directly support these formatters:
You need to use a Formatter, following code uses NumberFormat
Found this example... Will test...
Tested this and:
Both work, for my purposes I think String.Format is better and more succinct.
If performance is important in your case you could do it yourself with less overhead compared to the
String.format
function:Performance
Result
Own function: 1697ms
String.format: 38134ms
You can use Google Guava:
Maven:
Sample code:
Note:
Guava
is very useful library, it also provides lots of features which related toCollections
,Caches
,Functional idioms
,Concurrency
,Strings
,Primitives
,Ranges
,IO
,Hashing
,EventBus
, etcRef: GuavaExplained
Use
java.lang.String.format(String,Object...)
like this:for zero-padding with a length of 5. For hexadecimal output replace the
d
with anx
as in"%05x"
.The full formatting options are documented as part of
java.util.Formatter
.