How can I pad an integers with zeros on the left?
How do you left pad an int with zeros in java when converting to a string?
I'm basically looking to pad out integers up to 9999 with the leading zeros (eg 1 = "0001").
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
.
如果您出于任何原因使用pre 1.5 Java,那么可以尝试使用Apache Commons Lang方法
org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Let's say you want to print 11
as 011
You could use a formatter : "%03d"
.
You can use this formatter like this:
int a = 11;
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
Alternatively, some java methods directly support these formatters:
System.out.printf("%03d", a);
链接地址: http://www.djcxy.com/p/8042.html
上一篇: 如何在Java中创建通用数组?
下一篇: 我怎样才能用左边的零填充整数?