How can I pad an integer with zeros on the left?
Asked Answered
L

19

1226

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).

Longsufferance answered 23/1, 2009 at 15:21 Comment(4)
Yup, that's it! my bad... I typed it in on my phone. You dont' need the "new String" either : Integer.toString(num+10000).subString(1) works.Bleary
Long.valueOf("00003400").toString(); Integer.valueOf("00003400").toString(); --->3400Peterus
see also #35521778 for a solution with diagramErtha
There is a problem with the new String(Integer.toString(num + 10000)).substring(1) approach if num is any bigger than 9999 though, ijs.Euthenics
C
1968

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.

Cosher answered 23/1, 2009 at 15:26 Comment(9)
Should I expect the options in String.format to be akin to printf() in C?Newsprint
If you have to do this for a large list of values, performance of DecimalFormat is at least 3 times better than String.format(). I'm in the process of doing some performance tuning myself and running the two in Visual VM shows the String.format() method accumulating CPU time at about 3-4 times the rate of DecimalFormat.format().Diaghilev
@Shurane mostly, yes.Huonghupeh
And to add more than 9 zeros use something like %012dIgal
This is for Java 5 and above. For 1.4 and lower DecimalFormat is an alternative as shown here javadevnotes.com/java-integer-to-string-with-leading-zerosSchach
Long.valueOf("00003400").toString(); Integer.valueOf("00003400").toString(); --->3400Peterus
To get "0001" (four digits) as was asked for in the question you do "%04d". .Willem
Hi guys! I have some problems using: %d can't format java.lang.String argumentsLynsey
This only works to pad the String up to the number of characters specified in the format string. This does not add 5 zeros onto the String. More generally, this means you have to know that your string is between 0-N characters for a format string specified by "%0Nd". Any dynamic String that is longer than N, and this solution falls apart.Pippin
E
192

Let's say you want to print 11 as 011

You could use a formatter: "%03d".

enter image description here

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);
Ertha answered 20/2, 2016 at 11:41 Comment(5)
@Omar Koohei indeed, but it explains the reasoning behind the "magic constants".Ertha
Nice answer! Just a comment, the F of format() should be f: String.format(...);.Angeles
what if i dont want to append a leading 0 but another letter/number? thanksAllometry
@Allometry afaik it's not possible with the above formatting tools. In that case, I calculate the required leading characters (e.g. int prefixLength = requiredTotalLength - String.valueOf(numericValue).length), and then use a repeat string method to create the required prefix. There are various ways to repeat strings, but there isn't a native java one, afaik: #1235679Ertha
@Allometry starting from java 11 there is a String.repeat method though.Ertha
H
123

If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
Hemostat answered 23/1, 2009 at 15:32 Comment(0)
L
36

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.

Longsufferance answered 23/1, 2009 at 15:25 Comment(3)
Yes, I was going to suggest DecimalFormat because I didn't know about String.format, but then I saw uzhin's answer. String.format must be new.Medicare
It's similar how you'd do it in .Net Except the .Net way looks nicer for small numbers.Longsufferance
In my case I used the first option (DecimalFormat) because my number was a DoubleAbner
N
33

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
Nikaniki answered 25/6, 2018 at 14:26 Comment(0)
T
25

Here is how you can format your string without using DecimalFormat.

String.format("%02d", 9)

09

String.format("%03d", 19)

019

String.format("%04d", 119)

0119

Thorpe answered 19/2, 2020 at 3:48 Comment(0)
F
23

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

Formenti answered 3/9, 2013 at 15:5 Comment(4)
Above there's a mention of using DecimalFormat being faster. Did you have any notes on that?Kentonkentucky
@Kentonkentucky For DecimalFormat performance see also: #8554172Fireproof
Shocking! It's nuts that function works so poorly. I had to zero pad and display a collection of unsigned ints that could range between 1 to 3 digits. It needed to work lightning fast. I used this simple method: for( int i : data ) strData += (i > 9 ? (i > 99 ? "" : "0") : "00") + Integer.toString( i ) + "|"; That worked very rapidly (sorry I didn't time it!).Felizio
How does the performance compare after it's been run enough for HotSpot to have a crack at it?Radicalism
Y
18

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

Yellowstone answered 3/5, 2015 at 7:42 Comment(2)
Above sample code is usage only, not really sample code. The comment reflect this, you would need "String myPaddedString = Strings.padStart(...)"Conde
This method actually gives much better performance results than JDK String.format / MessageFormatter / DecimalFormatter.Donoghue
D
3

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(",",""));  
 }    
}  
Discomfort answered 2/3, 2012 at 19:13 Comment(0)
C
3
int x = 1;
System.out.format("%05d",x);

if you want to print the formatted text directly onto the screen.

Catfish answered 24/8, 2013 at 13:29 Comment(2)
But OP never asked for it. Internally String.format and System.out.format call the same java.util.Formatter implementation.Mogerly
... and System.out can be redirected.Radicalism
U
1

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

Unpeople answered 8/11, 2017 at 10:30 Comment(0)
E
1

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

Ec answered 13/10, 2018 at 11:15 Comment(1)
In this case the output is 0811.Eucharist
P
1

In Kotlin, you can use format() function.

val minutes = 5
val strMinutes = "%02d".format(minutes)

where, 2 is the total number of digits you want to display(including zero).

Output: 05

Pennyworth answered 4/4, 2023 at 11:57 Comment(0)
A
1

If you are on Java 15 and above,

var minutes = 5
var strMinutes = "%02d".formatted(minutes)

where, 2 is the total number of digits you want to display(including zero).

Output: 05

This uses formatted method part of instance method on Strings called which does the same as the static String.format(str,x,y,z)

Audile answered 2/12, 2023 at 13:46 Comment(0)
R
0

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);
Rameau answered 24/7, 2014 at 10:29 Comment(3)
(new char[diff]) whyWillams
replace("\0", "0")what is... whatWillams
@Willams - First I created a char array, and using that char array I created a string. Then I replaced null character(which is the default value of char type) with "0" (which is the char we need here for padding)Rameau
T
0

You can add leading 0 to your string like this. Define a string that will be the maximum length of the string that you want. In my case i need a string that will be only 9 char long.

String d = "602939";
d = "000000000".substring(0, (9-d.length())) + d;
System.out.println(d);

Output : 000602939

Totality answered 1/11, 2021 at 8:49 Comment(0)
A
0

Use this simple Kotlin Extension function

fun Int.padWithZeros(): String {
   return this.toString().padStart(4, '0')
}
Amid answered 4/3 at 16:2 Comment(0)
R
-3

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.

Recording answered 9/5, 2017 at 12:27 Comment(1)
Hmm...I like it.Uralic
A
-4

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

Acetophenetidin answered 15/8, 2020 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.