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
).
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
.
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
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:
/**
* @param in The integer value
* @param fill The number of digits to fill
* @return The given value left padded with the given number of digits
*/
public static String lPadZero(int in, int fill){
boolean negative = false;
int value, len = 0;
if(in >= 0){
value = in;
} else {
negative = true;
value = - in;
in = - in;
len ++;
}
if(value == 0){
len = 1;
} else{
for(; value != 0; len ++){
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if(negative){
sb.append('-');
}
for(int i = fill; i > len; i--){
sb.append('0');
}
sb.append(in);
return sb.toString();
}
Performance
public static void main(String[] args) {
Random rdm;
long start;
// Using own function
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
lPadZero(rdm.nextInt(20000) - 10000, 4);
}
System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.format
rdm = new Random(0);
start = System.nanoTime();
for(int i = 10000000; i != 0; i--){
String.format("%04d", rdm.nextInt(20000) - 10000);
}
System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
}
Result
Own function: 1697ms
String.format: 38134ms
You can use Google Guava:
Maven:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
Sample code:
String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
Note:
Guava
is very useful library, it also provides lots of features which related to Collections
, Caches
, Functional idioms
, Concurrency
, Strings
, Primitives
, Ranges
, IO
, Hashing
, EventBus
, etc
Ref: GuavaExplained
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.
import java.text.NumberFormat;
public class NumberFormatMain {
public static void main(String[] args) {
int intNumber = 25;
float floatNumber = 25.546f;
NumberFormat format=NumberFormat.getInstance();
format.setMaximumIntegerDigits(6);
format.setMaximumFractionDigits(6);
format.setMinimumFractionDigits(6);
format.setMinimumIntegerDigits(6);
System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));
System.out.println("Formatted Float : "+format.format(floatNumber).replace(",",""));
}
}
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
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
int number=2;
int requiredLengthAfterPadding=4;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.
/**
*
* @author Dinesh.Lomte
*
*/
public class AddLeadingZerosToNum {
/**
*
* @param args
*/
public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));
System.out.println(getLeadingZerosToNum(7));
System.out.println(getLeadingZerosToNum(13));
System.out.println(getLeadingZerosToNum(713));
System.out.println(getLeadingZerosToNum(7013));
System.out.println(getLeadingZerosToNum(9999));
}
/**
*
* @param num
* @return
*/
private static String getLeadingZerosToNum(int num) {
// Initializing the string of zeros with required size
String zeros = new String("0000");
// Validating if num value is less then zero or if the length of number
// is greater then zeros configured to return the num value as is
if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
return String.valueOf(num);
}
// Returning zeros in case if value is zero.
if (num == 0) {
return zeros;
}
return new StringBuilder(zeros.substring(0, zeros.length() -
String.valueOf(num).length())).append(
String.valueOf(num)).toString();
}
}
Input
0
7
13
713
7013
9999
Output
0000
0007
0013
7013
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.
new String(Integer.toString(num + 10000)).substring(1)
approach ifnum
is any bigger than 9999 though, ijs. – Felype