C# convert int to string with padding zeros?



Answers

i.ToString("D4");

See MSDN on format specifiers.

Question

In C# I have an integer value which need to be convereted to string but it needs to add zeros before:

For Example:

int i = 1;

When I convert it to string it needs to become 0001

I need to know the syntax in C#.




int p = 3; // fixed length padding
int n = 55; // number to test

string t = n.ToString("D" + p); // magic     

Console.WriteLine("Hello, world! >> {0}", t);

// outputs: 
// Hello, world! >> 055



C# 6.0 style string interpolation

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";



To pad int i to match the string length of int x, when both can be negative:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')



You can use:

int x = 1;
x.ToString("0000");



Links