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
  • 442
  • 8
  • 19

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://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
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
  • 180,369
  • 20
  • 160
  • 215
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")