- Home /
int length control? 3 should be 0003
Sorry if this is a very basic question about coding but I have not found the answer despite looking. I was not sure how to form the question.
I am going to have int coming in like 10 and 40 and 63 and 342 and I would like to turn them all into 0010 0040 0342. They all need to have a length of 4 digits.
Thank you.
Answer by Bunny83 · Aug 17, 2013 at 09:15 PM
This question has been asked a couple of times and even **today**.
Just use ToString like this:
someStringVariable = someIntVariable.ToString("0000");
I always knew about tostring but I did not know that you could feed it "0000" like that. I thought there was a direct way to manipulate the length of the int but this is perfect. Sorry for the repeat question.
Answer by Slobdell · Aug 17, 2013 at 08:50 PM
Change to a string
// Length of number
int numLength = 4;
// this is the number
int num = 25
// num as a string
string numString = num.toString();
// get number of 0s needed
int numZeros = numLength - numString.length();
string newNum;
for(int i = 0; i < numZeros; i++){
newNum += "0";
}
newNum += numString;
// your newNum will now be "0025"
The string class already have a padding function:
string someString = "25";
someString = someString.PadLeft(4,'0');
// someString == "0025"
btw: It's ToString not toString ;)
Your answer