views:

148

answers:

8

I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)

Is there a way to fix this? Thanks in advance.

Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.

+5  A: 

If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.

You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.

Thilo
Unsliced
A: 

No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.

Ignacio Vazquez-Abrams
+1  A: 

If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:

x.toString().Length <= 7

or better:

x < 10000000
Kobi
+1  A: 

Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.

Christian Severin
A: 

You should use string to check length count including 0.

Then I would like to ask "Why do you want to show 0000007? For What?"

RedsDevils
+1  A: 

I think you could format it as a string:

int myInt=1;
myInt.ToString("0000000");

prints:

0000001.

so you could do:

if (myInt.ToString("0000000").Length==7)
Sam Holder
A: 

You said you're asking for a int, but I suppose you're receiving it as string:

int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
    //if (i.ToString().Length == 7) // you can try this too
    if (i > 999999 && i < 10000000)
    {
        Console.WriteLine("Have exactly 7 digits");
    }
    else
    {
        Console.WriteLine("Doesn't have exactly 7 digits");
    }
}
else
{
    Console.WriteLine("Not an Int32 number");
}

This way you try to cast that received number as Int32 and, so, compare its length.

Rubens Farias
+1  A: 

You can simply write:

int input = 5;
if(input.ToString("0000000").Length == 7)
{
    //do your stuff
}
Bhaskar