New To Java - String format dynamic padding

String.format("%08d", myInt) will return a string 0 padded to a width of 8. But is there a way to have the amount of padding determined from a variable instead of having ot hardcode 8 in there? So if my program determines the padding needs to be X it can just use X in the String.format() method somehow?

I didn't see it in the API, but I may have overlooked it. I'm using Java 1.5

Thanks

[409 byte] By [phupa] at [2007-11-26 23:16:20]
# 1

String.format("%08d", myInt) will return a string 0

padded to a width of 8. But is there a way to have

the amount of padding determined from a variable

instead of having ot hardcode 8 in there?

Like so...?

public class FormatTest {

public static void main( String [] args ) {

int myInt = 2473;

int eight = 8;

System.out.println( String.format("%0"+ eight + "d", myInt) ); // Prints 00002473

}

}

kevjavaa at 2007-7-10 14:16:46 > top of Java-index,Java Essentials,New To Java...
# 2
That works. It makes my format strings really hard to read, but it works.I got caught up looking for somethign builtin and didn't even consider something like that. I'm used to python where you can use "%0*d" and pass an argument for the *.Thanks
phupa at 2007-7-10 14:16:46 > top of Java-index,Java Essentials,New To Java...
# 3

What about this:

import java.util.Formatter ;

public class FormatTest {

public static void main( String [] args ) {

int myInt = 2473;

int eight = 8;

String format = new Formatter().format("%%0%dd%%n", eight).toString();

System.out.format(format, myInt); // Prints 00002473

}

}

:-))

DrLaszloJamfa at 2007-7-10 14:16:46 > top of Java-index,Java Essentials,New To Java...
# 4
yeah, i guess a meta approach works too, and it's (a little) easier to see what the format is. similar to what you did is[code]int width = 8;int myInt = 2473;String result = String.format(String.format("%%0%dd", width), myInt);[/code]Thanks for the help.
phupa at 2007-7-10 14:16:46 > top of Java-index,Java Essentials,New To Java...