force string made from integer to be n-digit

Discussion in 'Java' started by Thomas Jollans, Feb 2, 2004.

  1. Is there a function (or way) to make 1 (an int) to "01", 16 to "16", 3
    to "03"...? I will also need to do this with 4-digit numbers.

    thomas
     
    Thomas Jollans, Feb 2, 2004
    #1
    1. Advertising

  2. Thomas Jollans wrote:

    > Is there a function (or way) to make 1 (an int) to "01", 16 to "16", 3
    > to "03"...? I will also need to do this with 4-digit numbers.
    >
    > thomas


    Something like:

    int REQUIRED_LENGTH = 4;

    String s = String.valueOf("5");
    int sizeDiff = REQUIRED_LENGTH - s.size();

    StringBuffer prefix = new StringBuffer();
    for(int i = 0;i<sizeDiff;i++){
    prefix.append("0");
    }
    prefix.append(s);

    s = prefix.toString;


    should work.

    --
    Kind regards,
    Christophe Vanfleteren
     
    Christophe Vanfleteren, Feb 2, 2004
    #2
    1. Advertising

  3. Thomas Jollans

    Carl Howells Guest

    Thomas Jollans wrote:
    > Is there a function (or way) to make 1 (an int) to "01", 16 to "16", 3
    > to "03"...? I will also need to do this with 4-digit numbers.
    >
    > thomas


    Take a look at java.text.DecimalFormat.
     
    Carl Howells, Feb 2, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Fangs
    Replies:
    3
    Views:
    9,839
    darshana
    Oct 26, 2008
  2. Harlin Seritt
    Replies:
    5
    Views:
    307
    Facundo Batista
    Apr 1, 2005
  3. Randy Kramer
    Replies:
    12
    Views:
    383
    Robert Klemme
    Oct 25, 2007
  4. Bunyip Bluegum

    Validate form for 4-digit integer

    Bunyip Bluegum, Sep 16, 2003, in forum: Javascript
    Replies:
    5
    Views:
    111
    Dr John Stockton
    Sep 18, 2003
  5. tudorc11
    Replies:
    0
    Views:
    405
    tudorc11
    May 18, 2013
Loading...

Share This Page