如何将两个数字字符串相加? [英] How to add two strings that are numbers?
问题描述
我正在遍历一些节点并获取电荷并将它们加在一起.尽管收费是字符串类型.
i am looping through some nodes and getting the charge and adding them together. the charge is of type string though.
第一次循环字符串charge = "309",
first time it loops string charge = "309",
第二次循环字符串charge = "38";
second time it loop string charge = "38";
`Looping through list of nodes
{
saBillDetail.TotalServiceUsage += totalSvcNode.InnerText;
}
`
我原以为我可以将它们加在一起,但它们却像这样连接起来:
I would have expected that I could add them together, but they are being concatenated instead like this:
`charge + charge = '30938'`
如何强制将这些字符串视为数字?并在循环结束时得到这样的输出
How can I force these strings to be treated as numbers? and get output like this at the end of the loop
`charge + charge = '347'`
推荐答案
因为人们已经回答了这也许是另一种解决方案所以你不会出错
As people allready answered this maybe another solution So you don't get errors
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return iOne + iTwo;
}
或者如果你想要一个字符串结果.
Or if you want a string result.
private static String AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return (iOne + iTwo).ToString();
}
正如 Alexei Levenkov 所说,您可以/应该处理异常.也许这样的事情会在开发过程中对您有所帮助
As Alexei Levenkov stated you could/should handle exceptions. Maybe something like this will help you during development
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
bool successParseOne = Int32.TryParse(one, out iOne);
bool successParseTwo = Int32.TryParse(two, out iTwo);
if (!successParseOne)
{
throw new ArgumentException("one");
}
else if(!successParseTwo)
{
throw new ArgumentException("two");
}
return (iOne + iTwo);
}
因此,当您输入错误号码时,您会在使用 try/catch 时收到通知
So when you have a wrong number you will be notified if you use try/catch
这篇关于如何将两个数字字符串相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!