www.webdeveloper.com
Results 1 to 5 of 5

Thread: Numeric string formatting with padding

  1. #1
    Join Date
    Nov 2003
    Location
    Derby, UK
    Posts
    87

    Numeric string formatting with padding

    Does anybody know how to create padded string formatting when dealing with numerics?
    In C++ you would write printf("%08ld",123), and you would get "00000123", but I can't find an equivalent with String.Format("{0}",123)
    As powerful as they claim their new formatting stuff to be, I cannot find out what the format string is to do the same with C#.

    Any ideas?
    Cheers,
    Tom
    I am not young enough to know everything - Oscar Wilde

  2. #2
    Join Date
    Nov 2003
    Posts
    655
    Try this: String.Format("{0:00000000}",123)

    An alternative if the number is in a variable is:
    lNum.ToString("00000000")
    Last edited by CardboardHammer; 05-11-2004 at 09:39 AM.

  3. #3
    Join Date
    Nov 2003
    Location
    Derby, UK
    Posts
    87
    Thank you for your reply, but that will not work - you will simply get a string of eight zeros.

    I've managed to finally find out (after attempting to decrypt Visual Studios On-Line help on formatting) that you do the following...
    Code:
    String.Format("{0:D8}",123);
    0 = the 1st parameter
    : = format separator
    D = it's a decimal number
    8 = the number of spaces to use ('0' character is used as default)
    I am not young enough to know everything - Oscar Wilde

  4. #4
    Join Date
    Nov 2003
    Posts
    655
    I was edit happy, so maybe you were referring to an older version of what I had, but String.Format("{0:00000000}",123) and lNum.ToString("00000000") both work. (Just tested them in a console app.)

  5. #5
    Join Date
    Aug 2006
    Location
    Netherlands
    Posts
    1
    If you use the {0:D8} format specification, just be sure to have an integer (or another numeric data type) as argument. If you pass a string, it will not work.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles