int number = 1;
//D4 = pad with 0000
string outputValue = String.Format("{0:D4}", number);
Console.WriteLine(outputValue);//Prints 0001
//OR
outputValue = number.ToString().PadLeft(4, '0');
Console.WriteLine(outputValue);//Prints 0001 as well
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
.ToString().PadLeft(4, '0') // that will fill your number with 0 on the left, up to 4 length
int i = 1;
i.toString().PadLeft(4,'0') // will return "0001"
public static string ToLeadZeros(this int strNum, int num)
{
var str = strNum.ToString();
return str.PadLeft(str.Length + num, '0');
}
// var i = 1;
// string num = i.ToLeadZeros(5);
}
//
//
///<summary>Format a value with a fixed number of digits.</summary>
public static string Pad( this long v, int digits ) {
int negative = 0;
if ( v < 0 ) {
negative = 1;
v = Math.Abs( v );
}
var source = v.ToString();
var length = source.Length;
int max = length;
if ( max < digits ) {
max = digits;
}
max += negative;
var ca = new char[ max ];
for ( int i = 0; i < max; i++ ) {
ca[ i ] = '0';
}
while ( length > 0 ) {
ca[ --max ] = source[ --length ];
}
if ( 0 != negative ) ca[ 0 ] = '-';
return new string( ca );
}