How do I add two strings in C#?

Asked

Viewed 718 times

7

I have a method that will take two strings and return the sum of them in string format.

I use string because there will be +-30 digit numbers. I’m having trouble converting to add. :/

2 answers

6


How do you talk about converting to ulong I’ll assume that the strings represent whole.

public string Somar(string numA, string numB)
{
    BigInteger bigA = BigInteger.Parse(numA);
    BigInteger bigB = BigInteger.Parse(numB);
    return BigInteger.Add(bigA, bigB).ToString();
}

If you want to treat float or double change Biginteger for Bigdecimal. An exception of the kind Formatexception will be launched if it is not possible to do the Parse.

  • I only need one () at the end of Tostring right? : D

3

If you are using . Net Framework 4.0 or higher you can use Biginteger. You only need to reference the following Assembly System.Numerics.

  • I use . NET 4.5.2, but it does not find Biginteger. http://prntscr.com/7fvinq

  • @Jonathanbarcela vc needs to add the System.Numerics reference to your project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.