0

Just bumped into this line of code:

string sNumFormat = new string('0', Convert.ToString(totalCount).Length);

where totalCount is an integer.

It's used here:

kNewComp.Name
    = baseName + string.Format("{0:" + sNumFormat + "}", 1 + componentIndex);

I'm pretty sure this is just an interesting way of ensuring numbers are padded with leading zeroes, but I haven't seen it expressed quite like this before.

Is there a more standard way of achieving the same effect?

MarcinJuraszek
  • 121,297
  • 15
  • 183
  • 252
Sean Anderson
  • 26,361
  • 27
  • 120
  • 228
  • As your code already works, this would fit better on [Code Review](http://codereview.stackexchange.com/). Also, take a look at [String.PadLeft](http://msdn.microsoft.com/en-us/library/system.string.padleft%28v=vs.110%29.aspx) – Pierre-Luc Pineault Feb 15 '14 at 00:51

1 Answers1

1
NewComp.Name = baseName + string.Format("{0:" + sNumFormat + "}", 1 + componentIndex);

Can be replaced with

var s = (1 + componentIndex).ToString();
var digits = (int) (Math.Ceiling(Math.Log10(totalCount)));
Console.Write(s.PadLeft(digits, '0'));

And then you can get rid of sNumFormat.

Note that converting to string is not a good way to measure digits. See: Get number of digits before decimal point

Community
  • 1
  • 1
Superbest
  • 23,790
  • 12
  • 57
  • 132