586

Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)

static String intToString(int num, int digits) {
    StringBuffer s = new StringBuffer(digits);
    int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1; 
    for (int i = 0; i < zeroes; i++) {
        s.append(0);
    }
    return s.append(num).toString();
}
Nate Parsons
  • 14,431
  • 13
  • 51
  • 67
  • 1
    You should change accepted answer to @begray one. His is far better for the vast majority of applications and for a changeable amount of zeroes you can use `String.format("%0" + digits + "d", num);` – t.pimentel Sep 01 '14 at 13:59
  • 2
    Sure. At the time, I accepted Elijah's because my project was locked into Java 1.4, but I don't think that's worth misdirecting 100k other users into what happened to work for me. – Nate Parsons Sep 17 '14 at 00:08
  • I've voted to close as a duplicate. While this question was asked first, I think the duplicate is slightly clearer to read and seems to be the canonical question (based on up-votes and view count). – Duncan Jones Sep 23 '14 at 08:24
  • @Duncan, why would you mark a 6 year old question as duplicate? – Angel Koh Jun 19 '15 at 08:03
  • 2
    @AngelKoh I explained why in my comment. – Duncan Jones Jun 19 '15 at 08:06

5 Answers5

1520

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3
fospathi
  • 537
  • 1
  • 6
  • 7
begray
  • 15,911
  • 4
  • 22
  • 14
  • If the number of digits is variable (e.g. provided as an argument), the above method although elegant may not be suitable. – Santosh Tiwari Feb 13 '13 at 16:43
  • 67
    Santhosh... Just dynamically make the format string `String.format("%0" + paddingSize + "d", num)` – mlathe Mar 21 '13 at 23:41
  • @Fran except GWT ones, i suppose – Andrey Regentov Feb 03 '14 at 08:31
  • 17
    Wanted to point out that this solution might be buggy: it produces different results depending on the default locale because String.format is LOCALE-SPECIFIC. There are many locales that do NOT use Arabic numerals 0-9 (oddly enough, Arabic is one of those locales). I had a bug where my code was crashing on Android when the phone was set in Arabic because I was formatting a date string using String.format("%04d-%02d-%02d", year, month, day), thinking that would produce an ISO 8601 date, but it produces something like "٢٠١٤-٠٨-٠٦" when the phone is in Arabic. – adevine May 09 '14 at 21:15
  • 10
    @adevine you can avoid this bug by specifying the local you want ex: Local.US, for Arab users it's so handy to use Arabic digits, just call `String.format(Local.US, string, params)` – Walid Ammar Jul 31 '14 at 14:03
  • 3
    `String formatted = String.format((Locale) null, "%05d", yourLongNumber);` should also work and is safer for some languages... – StefanTo Sep 22 '16 at 11:35
  • wow, that old folk really helped... – ArifMustafa Jun 28 '18 at 02:30
94

Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:

String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;

In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

%% --> %
0  --> 0
%d --> <value of digits>
d  --> d

So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.

Boken
  • 4,825
  • 10
  • 32
  • 42
Jason Coco
  • 77,985
  • 20
  • 184
  • 180
  • See begray's answer which uses the correct flags to zero pad a 3 character wide output. – Robert Sep 05 '12 at 19:47
  • 3
    @Robert It does set the correct width. It's the same exact thing as bergay's answer except that the padding is added programmatically using the same interface. Did you simply glance at the format string and decide it was incorrect without looking to see what the code was actually doing? – Jason Coco Sep 05 '12 at 21:17
  • 2
    It seems unneccessary to use `String.format()` twice, just use string concatenation: `String.format("%0" + digits + "d", num)` – icza Aug 21 '14 at 12:22
  • If Java 1.4 and below, try new DecimalFormat("00000").format(123); as shown here http://javadevnotes.com/java-integer-to-string-with-leading-zeros – JavaDev Mar 05 '15 at 03:37
39

Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
Elijah
  • 13,368
  • 10
  • 57
  • 89
8

How about just:

public static String intToString(int num, int digits) {
    String output = Integer.toString(num);
    while (output.length() < digits) output = "0" + output;
    return output;
}
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
Torin Rudeen
  • 115
  • 1
  • 1
  • 3
    (1) That's going to return 0num0num0num etc, instead of 00000num (2) Lots of string concatenations with "+" are a bad idea performance-wise. Better to preallocate a StringBuffer or StringBuilder of length 'digits' – Nate Parsons Mar 29 '11 at 15:58
  • 8
    "(1) That's going to return 0num0num0num etc, instead of 00000num" - You are wrong with this comment... `num` is not within the loop. – Nappy Jul 11 '11 at 10:26
  • @Nappy you are right, not sure why I didn't see it at the time. – Nate Parsons Aug 13 '12 at 01:57
-12

In case of your jdk version less than 1.5, following option can be used.

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    sTest.append(String.valueOf(iTest));
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));