Add numbers in c#

2019-01-29 02:13发布

问题:

i have a numerical textbox which I need to add it's value to another number I have tried this code

String add = (mytextbox.Text + 2)

but it add the number two as another character like if the value of my text box is 13 the result will become 132

回答1:

String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();

You need to convert the text to an integer to do the calculation.



回答2:

The type of mytextbox.Text is string. You need to parse it as a number in order to perform integer arithmetic, e.g.

int parsed = int.Parse(mytextbox.Text);
int result = parsed + 2;
string add = result.ToString(); // If you really need to...

Note that you may wish to use int.TryParse in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:

int parsed;
if (int.TryParse(mytextbox.Text, out parsed))
{
    int result = parsed + 2;
    string add = result.ToString();
    // Use add here    
}
else
{
    // Indicate failure to the user; prompt them to enter an integer.
}


回答3:

const int addend = 2; 
string myTextBoxText = mytextbox.Text;
var doubleArray = new double[myTextBoxText.ToCharArray().Length];
for (int index = 0; index < myTextBoxText.ToCharArray().Length; index++)
{
    doubleArray[index] = 
        Char.GetNumericValue(myTextBoxText.ToCharArray()[index]) 
        * (Math.Pow(10, (myTextBoxText.ToCharArray().Length - 1) - index));
}
string add  = 
    (doubleArray.Aggregate((term1, term2) => term1 + term2) + addend).ToString();


回答4:

string add=(int.Parse(mytextbox.Text) + 2).ToString()

if you want to make sure the conversion doesn't throw any exception

  int textValue = 0;
  int.TryParse(TextBox.text, out textValue);
  String add = (textValue + 2).ToString();


回答5:

int intValue = 0;
if(int.TryParse(mytextbox.Text, out intValue))
{
    String add = (intValue + 2).ToString();
}

I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)



回答6:

You can use the int.Parse method to parse the text content into an integer:

String add = (int.Parse(mytextbox.Text) + 2).ToString();


回答7:

Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.

This might be a good approach if you need to reuse the integer several times:

private int MyTextBoxInt
{
    get
    {
        return Int32.Parse(mytextbox.Text);
    }
}

And then you can use the property like this:

int result = this.MyTextBoxInt + 2;


标签: c# numbers add