Kirsty White
Kirsty White

Reputation: 1220

Integer comparison C#

I have a textbox that a user inputs 9 numbers. I am trying to compare the last two digits of this number to myInt:

        int myInt = 34;
        int numberToCompare = Convert.ToInt32(textBox1.Text);
        if (numberToCompare == myInt)
        {
            MessageBox.Show("Vat number correct");
        }

If the textbox input is equal to say: 876545434 how can I chop of the remaining numbers: 8765454(34) which I can then compare to myInt? The textbox number will always remain 9 digits!

Update:

I managed it with this method:

        int myInt = 34;
        int numberToCompare = Convert.ToInt32(textBox1.Text.Substring(7,2));
        if (numberToCompare == myInt)
        {
            MessageBox.Show("Vat number correct");
        }
        else
        {
            MessageBox.Show("Vat number incorrect");
        }

But I would like to know why this is a bad method?

Upvotes: 0

Views: 1323

Answers (4)

Gary Walker
Gary Walker

Reputation: 9144

Not being ideal in lots of ways, but the string class has the EndsWith() method. If it EndsWith "34" you would have a match. Certainly a simple solution.

Upvotes: 7

DotNetRussell
DotNetRussell

Reputation: 9865

String txtBoxInput = "1234567890";

try{
    //Some validation for Servy
   if(txtBoxInput!=null && txtBoxInput is String && txtBoxInput.Length>1)
   {
     String last2Numbs = txtBoxInput.Substring(txtBoxInput.Length-2);

     Int32 lasst2NumbersInt;
     bool result = Int32.TryParse(last2Numbs, out last2NumbsInt);

     if(result && last2NubsInts == MyInt)
       MessageBox.Show("Vat number correct");
     }
}
catch(Exception ServysException)
{
    MessageBox.Show("Uhhhh ohh! An over engineered simple answer threw an error: " + ServysException.Message);
}

Upvotes: 0

Micah Armantrout
Micah Armantrout

Reputation: 7001

if textbox1.text = 876545434

if(txtBoxInput.length >  4)
{
   Textbox1.text.substring( txtBoxInput.length - 2 ,2)
}

will give you 34

Upvotes: 0

Neil Hampton
Neil Hampton

Reputation: 1883

    int myInt = 34;
    int numberToCompare = Convert.ToInt32(textBox1.Text);
    if ((numberToCompare % 100) == myInt)
    {
        MessageBox.Show("Vat number correct");
    }

Upvotes: 0

Related Questions