0

I have a very simple Question to ask.

I have a string like:

         string str="89";

I want to format my string as follow :

         str="000089";

How can i achieve this?

Mubsher Mughal
  • 422
  • 8
  • 18

3 Answers3

9

Assuming the 89 is actually coming from another variable, then simply:

    int i = 89;
    var str = i.ToString("000000");

Here the 0 in the ToString() is a "zero placeholder" as a custom format specifier; see https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
6

If you have a string (not int) as the initial value and thus you want to pad it up to length 6, try PadLeft:

   string str = "89";

   str = str.PadLeft(6, '0');
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
2

If you want the input to be a string you'll have to parse it before you output it

int.Parse(str).ToString("000000")