converting odd number digits to even number

G

Guest

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.
 
M

Marc Gravell

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
 
P

Peter Duniho

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
 
M

Mythran

Vinki said:
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top