1

I want to convert a number to a string but have the number formatted with 10 digits. For example, if the number is 5, the string should be "0000000005". I checked the formatting of strings at:

http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

but there isn't any format that lets you specify the number of digits.

Actually the "0" placeholder would work but in reality I need 100 places, so I'm not going to use the "0" placeholder.

Johann
  • 27,536
  • 39
  • 165
  • 279
  • Have you read the documentation? http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx, or more specifically, http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#DFormatString – Nicholas Carey Jan 08 '14 at 18:12
  • @NicholasCarey not really with the requirements to have 100 leading zero... – Steve Jan 08 '14 at 18:16

3 Answers3

2

You can use the ToString formatting Dn to output leading zeroes:

var d = 5;
var s2 = d.ToString("D2");
var s10 = d.ToString("D10");
Console.WriteLine(s2);
Console.WriteLine(s10);

The output is:

05
0000000005
keenthinker
  • 7,645
  • 2
  • 35
  • 45
  • Any reason why the "D" is not listed with the other placeholders on the link I gave? – Johann Jan 08 '14 at 18:07
  • Yes - Dn is a **standard** formatting option and not a custom one: [MSDN article](http://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx) – keenthinker Jan 08 '14 at 18:10
  • @Steve i didn't knew the limits of the standard formatting - it seems 99 is the upper limit defined by the .NET framework. – keenthinker Jan 08 '14 at 18:12
  • Neither me, I was testing in LinqPad and discoverd this truth. Oh well it is not a common situation I think – Steve Jan 08 '14 at 18:13
1

Normally the D specifier for standard numeric format strings is enough with its precision to format a number with the required number of leading zeros.
But it stops at 99 and if you really need 100 leading zeros you need to resort to the old trusty method of string concatenation and right truncation

int number = 5;
string leadingZero = new string ('0', 100) + number.ToString();
string result = leadingZero.Substring(leadingZero.Length - 100);
Steve
  • 213,761
  • 22
  • 232
  • 286
0

This page should help you find the solution you need: http://msdn.microsoft.com/en-us/library/dd260048(v=vs.110).aspx

DLeh
  • 23,806
  • 16
  • 84
  • 128