Search code examples
.netstringstring-formatting

String format in .NET: convert integer to fixed width string?


I have an int in .NET/C# that I want to convert to a specifically formatted string.

If the value is 1, I want the string to be "001".

10 = "010".

116 = "116".

etc...

I'm looking around at string formatting, but so far no success. I also won't have values over 999.


Solution

  • Take a look at PadLeft.

    ex:

    int i = 40;
    
    string s = i.ToString().PadLeft(3, '0'); 
    

    s == "040"