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.ToString("0000");
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
Simply
int i=123;
string paddedI = i.ToString("D4");
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");
C# 6.0 style string interpolation
int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";