-2

Given

int myNumber=6
int myDigits=4

how do I asssign

string myString = "0006"

I asssume it would use string.Format()

T.S.
  • 18,195
  • 11
  • 58
  • 78
SmileyFtW
  • 326
  • 2
  • 10

1 Answers1

1

You can do

string myString = 6.ToString().PadLeft(4, '0');
T.S.
  • 18,195
  • 11
  • 58
  • 78
  • if the number is 10 then won't pad left result in a 5 digit number? – SmileyFtW Dec 11 '19 at 23:34
  • @SmileyFtW 10 will get you `0010`. "4" is total number of characters in the result – T.S. Dec 11 '19 at 23:36
  • Perfect... thank you – SmileyFtW Dec 11 '19 at 23:38
  • the result was for a return string and looks like this and appears to do what I need `return _seqnumber.ToString().PadLeft(_seqNumDigits,'0')` – SmileyFtW Dec 11 '19 at 23:45
  • @SmileyFtW Glad it worked for you. The reason whey they downvoted is because you have not done your research. Well, happens. This also works `10.ToString("D4")` – T.S. Dec 11 '19 at 23:47
  • Well, I had done *some* homework I found `Format` and `PadLeft`. I am just now trying to learn C# coming from VBA. I googled and what I found seemed to indicate `PadLeft` was not what I wanted even though it turned out to be exactly what I needed. I know how to do a quick test in VBA, but don't have that skill in C# just yet. Thank you for the answer. I upvoted your solution as it was indeed the answer. – SmileyFtW Dec 12 '19 at 15:55
  • No problem. If this answers, you should also accept this answer. Another way to do - old programmer way - if you have max 5 chars, and you can have 1 to 5 initial chars, just concatenate `"0000" + val`. Then substring 5 last chars. But .net makes it all easy for you. All this is already built-in – T.S. Dec 12 '19 at 16:12