tags:

views:

4911

answers:

4

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();
}
+3  A: 

String.format (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be: String.format("%03d", num) - 0 - to pad with zeros, 3 - to set width to 3

begray
+7  A: 

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%dd", 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.

Jason Coco
Good to document when the mechanism became available.
Jonathan Leffler
+3  A: 

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);
}
Elijah
Thanks, I thought I was the only one pre-1.5 (1.4.2)
drhorrible
A: 

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()));
Madhu Subramanian