2017-06-10 66 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(); 
相关问题