4 Replies Latest reply: Mar 28, 2007 4:58 PM by 807599 RSS

    String format dynamic padding

    807599
      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
        • 1. Re: String format dynamic padding
          807599
          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
               }
          }
          • 2. Re: String format dynamic padding
            807599
            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
            • 3. Re: String format dynamic padding
              807599
              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
                  }
              }
              :-))
              • 4. Re: String format dynamic padding
                807599
                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
                int width = 8;
                int myInt = 2473;
                String result = String.format(String.format("%%0%dd", width), myInt);
                Thanks for the help.