Leading Zeros ( Format)
-
I am trying to format an integer to a string with leading zeros: This works: int i = 1234 Console.WriteLine("{0:0000000000}",i); But what about make formats for new strings or saving in string variables ? string strLine = new String("{0:00000}",i); --> Cannot work caused by constructor parameter collision. By the way, var "i" is generic. So no solutions with constants and other literals. Thanks for all advice in advance.
-
I am trying to format an integer to a string with leading zeros: This works: int i = 1234 Console.WriteLine("{0:0000000000}",i); But what about make formats for new strings or saving in string variables ? string strLine = new String("{0:00000}",i); --> Cannot work caused by constructor parameter collision. By the way, var "i" is generic. So no solutions with constants and other literals. Thanks for all advice in advance.
Ok, lets look under the hood of what works:
Console.WriteLine(string,params object[])
which you are calling internally callsConsole.Out.WriteLine(string, params object[])
Console.Out
is aTextWriter
instance, so:TextWriter.WriteLine(string, params object[])
Internally this callsString.Format(String,params object[] args);
so finally in answer to your question this will work:string strLine = String.Format("{0:00000}",i);
HTH ;) -
Ok, lets look under the hood of what works:
Console.WriteLine(string,params object[])
which you are calling internally callsConsole.Out.WriteLine(string, params object[])
Console.Out
is aTextWriter
instance, so:TextWriter.WriteLine(string, params object[])
Internally this callsString.Format(String,params object[] args);
so finally in answer to your question this will work:string strLine = String.Format("{0:00000}",i);
HTH ;)