Hello Everyone,
I am trying to convert the digits to even number so for example if I have
3 digit number, I want it to be 4 digit and If I have 5 digit number, I want
it to be 6 digit. How can i do it in C#
Below is what I am trying to di
number = 123
I want it to be
0123
and
23456
I want it o be
023456
Thanks.
Marc Gravell - 29 Jun 2007 22:58 GMT
Well, you can't do this to the "number", since the number itself
doesn't care about things like leading zeros. Just treat it as a
string...
string sVal = value.ToString(); // or whatever
if((sVal.Length % 2) == 1) { // odd length
sVal = "0" + sVal; // left-pad with zero
}
That do?
Marc
Peter Duniho - 29 Jun 2007 23:02 GMT
> I am trying to convert the digits to even number so for example if I
> have
> 3 digit number, I want it to be 4 digit and If I have 5 digit number, I
> want
> it to be 6 digit.
What if you already have a four-digit number? Should numbers with an even
count of digits be left alone?
Are you sure this isn't a homework assignment? Sure doesn't sound like
anything you'd find in non-academic code.
Anyway, the first step is to understand that until you've converted a
number to a string, based on some particular number base (base 10,
apparently in your case) there is no such idea as "number of digits".
Once you figure that out, then it's a simple matter to count the digits
and prepend the character '0' when needed.
Pete
John Timney (MVP) - 29 Jun 2007 23:35 GMT
string myNum = 123.ToString();
string fubar = ((myNum.Length % 2) == 1) ? "0" + myNum : myNum;
Good luck with your assignment!!
Regards
John Timney (MVP)
http://www.johntimney.com
http://www.johntimney.com/blog
> Hello Everyone,
>
[quoted text clipped - 15 lines]
>
> Thanks.
Mythran - 30 Jun 2007 01:07 GMT
> Hello Everyone,
>
[quoted text clipped - 15 lines]
>
> Thanks.
This seems to work (thought up and tested just now, but not fully tested):
int iNumber = 1234;
string sNumber = iNumber.ToString();
sNumber =
sNumber.PadLeft(sNumber.Length + (sNumber.Length % 2), '0');
Console.WriteLine(sNumber);
for 1234 it reads:
1234
for 12345 it reads:
012345
for 123456 it reads:
123456
for 1234567 it reads:
01234567
HTH,
Mythran