简体   繁体   中英

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?

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.

if textbox1.text = 876545434

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

will give you 34

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);
}
    int myInt = 34;
    int numberToCompare = Convert.ToInt32(textBox1.Text);
    if ((numberToCompare % 100) == myInt)
    {
        MessageBox.Show("Vat number correct");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM