2013-08-21 56 views
0

我有一個用戶輸入9個數字的文本框。我想這個號碼的最後兩位數字比較敏:整數比較C#

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

如果在文本框中輸入等於說:876545434我怎麼能砍剩下的數字:8765454(34)然後我就可以比較到myInt?文本框號碼將始終保持9位數!

更新:

 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"); 
     } 

但我想知道爲什麼這是一個壞方法:

我用這種方法管理的呢?

+0

聽起來你應該使用字符串,而不是'int's。記住:_如果你不能添加它,它不是一個數字_。 – SLaks

+0

你總是可以添加一個int tho?這是沒有意義的? –

+0

因爲如果你的字符串不是9個數字長的話 –

回答

7

在很多方面是不理想的,但串類具有的endsWith()方法。如果它結束與「34」,你會有一場比賽。當然一個簡單的解決方案。

+0

不錯!會試試看。 –

+0

你打敗了我...... upvoted :-) –

+0

什麼約-1234? –

0

如果textbox1.text = 876545434

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

會給你34

+2

這是非常低效的,而不是僅僅解析和使用mod。 –

+0

是的,事實是有多種方法來給貓皮。只取決於你想要完成的事情。在處理器上,今天做這1次並不重要。即使在循環中多次執行此操作也不會產生太大的影響 –

+0

此方法的輸入爲34,2,134等。 – Servy

0
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); 
} 
+0

你的答案會拋出一個輸入爲「0」的異常。 – Servy

+0

@Servy我剛剛更新它,以正確的語法。我只是跑它,它的工作 –

+0

如果字符串只有一個字符長度,它會給你'substring'的範圍錯誤的索引。 – Servy

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