Click to See Complete Forum and Search --> : Numeric string formatting with padding


tomhartland
05-11-2004, 03:30 AM
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

CardboardHammer
05-11-2004, 10:30 AM
Try this: String.Format("{0:00000000}",123)

An alternative if the number is in a variable is:
lNum.ToString("00000000")

tomhartland
05-11-2004, 10:38 AM
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...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)

CardboardHammer
05-11-2004, 10:44 AM
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.)

happy108
08-22-2006, 11:45 AM
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.