2017-06-10 117 views
0

我有一個字典,其中包含各種字符串,包括帶美元符號的字符串數字。我試圖添加兩個標籤在一起,但顯然是「$」不會解析。我使用try和catch:

 try 
     { 
      int total = 0; 
      total = int.Parse(priceLabel.Text) + int.Parse(totalLabel.Text); 
      totalLabel.Text = total.ToString(); 
     } 

     catch 
     { 
      MessageBox.Show("Error"); 
     } 

我不知道如何得到它的工作,priceLabel是具有「$」 attacthed之一。

+0

完全同樣的問題昨天。 – Rob

+0

我尋找這樣的問題,並沒有看到任何 – KobiashiMaru

回答

3

簡單的解決辦法是用空字符替換$

total = int.Parse(priceLabel.Text.Replace("$", "")) + int.Parse(totalLabel.Text); 
+0

感謝您的快速反應,很好的作品。 – KobiashiMaru

+0

@DavidNelson很高興能幫到你。請閱讀[this](https://stackoverflow.com/help/someone-answers) – CodingYoshi

+1

我做了所有這些,只需等待5分鐘即可接受答案。 – KobiashiMaru

2

你提到一本字典,但你的例子只能說明標籤,所以我們只處理標籤爲例(這個概念是不管字符串值的來源如何)。

decimal類型實際上有一個方法來處理貨幣符號。您可以使用以下代碼從字符串中獲取數字值。然後小數點可以在年底前轉換爲int如果這就是你要處理的類型(即,如果有一個在貨幣量沒有小數):

int total = (int)(decimal.Parse(priceLabel.Text, NumberStyles.Currency) + 
    decimal.Parse(totalLabel.Text, NumberStyles.Currency)); 

totalLabel.Text = total.ToString(); 
相關問題