Add numbers in c# - c#

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

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.
}

String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();
You need to convert the text to an integer to do the calculation.

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();

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();

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)

You can use the int.Parse method to parse the text content into an integer:
String add = (int.Parse(mytextbox.Text) + 2).ToString();

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;

Related

Simple addition string to int with C#

I have knowledge in PHP and I want to learn C # language but I do not even do simple addition.
I want to get the value of a ComboBox, convert this value to int and be able to add another value
Despite the conversion done, I have an error : Can not convert type "int" to "string.
My code :
private void btnValidate_click(object sender, RoutedEventArgs e)
{
int number = Test();
}
int Test()
{
string day = DayBirth.Text;
int number;
bool isNumeric = int.TryParse(day, out number);
if (isNumeric == false)
{
Resultat1.Text = "This is not a number";
}
else
{
Resultat1.Text = number + 10;
}
return number;
}
Thank you
The issue is that Resultat1.Text is expecting a string, not an int. You can do
Resultat1.Text = (number+10).ToString();
and it should work.
what you need to do is Converting your number to string after addition
Resultat1.Text = (number + 10).ToString;
Text property accept string value not integer so after addition you have to convert it as string
Resultat1.Text = (number + 10).ToString();

C#: Increment only the last number of a String

I have strings that look like this:
1.23.4.34
12.4.67
127.3.2.21.3
1.1.1.9
This is supposed to be a collection of numbers, separated by '.' symbols, similar to an ip address. I need to increment only the last digit/digits.
Expected Output:
1.23.4.35
12.4.68
127.3.2.21.4
1.1.1.10
Basically, increment whatever the number that is after the last '.' symbol.
I tried this:
char last = numberString[numberString.Length - 1];
int number = Convert.ToInt32(last);
number = number + 1;
If I go with the above code, I just need to replace the characters after the last '.' symbol with the new number. How do I get this done, good folks? :)
It seems to me that one method would be to:
split the string on . to get an array of components.
turn the final component into an integer.
increment that integer.
turn it back into a string.
recombine the components with . characters.
See, for example, the following program:
using System;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
String original = "1.23.4.34";
String[] components = original.Split('.');
int value = Int32.Parse(components[components.Length - 1]) + 1;
components[components.Length - 1] = value.ToString();
String newstring = String.Join(".",components);
Console.WriteLine(newstring);
}
}
}
which outputs the "next highest" value of:
1.23.4.35
You can use string.LastIndexOf().
string input = "127.3.2.21.4";
int lastIndex = input.LastIndexOf('.');
string lastNumber = input.Substring(lastIndex + 1);
string increment = (int.Parse(lastNumber) + 1).ToString();
string result = string.Concat(input.Substring(0, lastIndex + 1), increment);
You need to extract more than just the last character. What if the last character is a 9 and then you add 1 to it? Then you need to correctly add one to the preceding character as well. For example, the string 5.29 should be processed to become 5.30 and not simply 5.210 or 5.20.
So I suggest you split the string into its number sections. Parse the last section into an integer. Increment it and then create the string again. I leave it as an exercise for the poster to actually write the few lines of code. Good practice!
Something like this:
var ip = "1.23.4.34";
var last = int.Parse(ip.Split(".".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries).Last());
last = last + 1;
ip = string.Format("{0}.{1}",ip.Remove(ip.LastIndexOf(".")) , last);
If you are dealing with IP, there will be some extra code in case of .034, which should be 035 instead of 35. But that logic is not that complicated.
It's simple as this, use Split() and Join() String methods
String test = "1.23.4.34"; // test string
String[] splits = test.Split('.'); // split by .
splits[splits.Length - 1] = (int.Parse(splits[splits.Length - 1])+1).ToString(); // Increment last integer (Note : Assume all are integers)
String answ = String.Join(".",splits); // Use string join to make the string from string array. uses . separator
Console.WriteLine(answ); // Answer : 1.23.4.35
Using a bit of Linq
int[] int_arr = numberString.Split('.').Select(num => Convert.ToInt32(num)).ToArray();
int_arr[int_arr.Length - 1]++;
numberString = "";
for(int i = 0; i < int_arr.Length; i++) {
if( i == int_arr.Length - 1) {
numberString += int_arr[i].ToString();
}
else {
numberString += (int_arr[i].ToString() + ".");
}
}
Note: on phone so can't test.
My Solution is:
private static string calcNextCode(string value, int index)
{
if (value is null) return "1";
if (value.Length == index + 1) return value + "1";
int lastNum;
int myIndex = value.Length - ++index;
char myValue = value[myIndex];
if (int.TryParse(myValue.ToString(), NumberStyles.Integer, null, out lastNum))
{
var aStringBuilder = new StringBuilder(value);
if (lastNum == 9)
{
lastNum = 0;
aStringBuilder.Remove(myIndex, 1);
aStringBuilder.Insert(myIndex, lastNum);
return calcNextCode(aStringBuilder.ToString(), index++);
}
else
{
lastNum++;
}
aStringBuilder.Remove(myIndex, 1);
aStringBuilder.Insert(myIndex, lastNum);
return aStringBuilder.ToString();
}
return calcNextCode(value, index++);
}

Input String was not in a correct form

There are two text boxes called unitprice.txt and quantity.txt. there is another textbox called total.txt which keeps on getting updated as the when ever the user input unit price and quantity.
Oonce the user input these two those two textboxes are getting empty and total.txt getting updated by the total. it needs to be done continuously but in my code it is not and saying
INPUT STRING WASN'T IN A CORRECT FORM.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text) * int.Parse(quantitytxt.Text);
sum = int.Parse(total.Text) + tot;
total.Text = sum.ToString();
once the user enters the unit price and quantity total text boxe is updated by the toal. and again user enters the second item's unit price and quantity then previous value in total text box needs to be updated which means that new total generated from the second item needs to be added to previous total.(2500+3000=5500)
Hey it was solved but in this way.
int sum = 0;
private void button2_Click(object sender, EventArgs e)
{
try
{
sum += int.Parse(qtytxt.Text) * int.Parse(unitprice.Text);
total.Text = sum.ToString();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
First of all check if text box value is not coming empty or not,If it is coming empty then set 0 as default while converting to parse Int otherwise it will show exception. see below code it will help you.
int tot = 0;
int sum = 0;
tot = int.Parse(string.IsNullOrEmpty(unitprice.Text.Trim()) ? "0" : unitprice.Text.Trim()) * int.Parse(string.IsNullOrEmpty(quantitytxt.Text.Trim()) ? "0" : quantitytxt.Text.Trim());
sum = int.Parse(string.IsNullOrEmpty(total.Text.Trim()) ? "0" : total.Text.Trim()) + tot;
total.Text = sum.ToString();
You are trying to parse a string value that is textbox value to integer, so you shouldn't do like the above, because may be it contains empty string or null value too. So, follow the below method of conversion, so that errors may not occur.
tot = Convert.ToInt32(Convert.ToString(unitprice.Text)) * Convert.ToInt32(Convert.ToString(quantitytxt.Text));
Why you should follow the above method is, the Convert.ToString() will handle the null values and convert the null values to an Empty string and the Convert.ToInt32() will convert an empty string to 0 value.
If you want another option, you can try Int32.TryParse(a_string_here, an_out_int_here);
For more, look at the documentation here:MSDN TryParse
It'll take a string and try to parse it to a valid int... if it fails, it returns 0.
int a ;
Int32.TryParse("5",out a);
System.Out.WriteLine("a="+a); // Will be: a=5
Int32.TryParse("e",out a);
System.Out.WriteLine("a="+a); // Will be: a=0
First of all check if text box value is not coming empty, as if you will parse it into Int and when its empty, there will be this or similar exception.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text!=String.Empty?unitprice.Text:"0") * int.Parse(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = int.Parse(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
You can also try:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text!=String.Empty?unitprice.Text:"0") * Convert.ToInt32(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = Convert.ToInt32(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
Try this:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text.Replace(" ", "")) * Convert.ToInt32(quantitytxt.Text.Replace(" ", ""));
sum = Convert.ToInt32(total.Text.Replace(" ", "")) + tot;
total.Text = sum.ToString();
If this throws an exception your textboxes probably has unwanted characters (i.e. commas: "1,000.00" or letters) or empty that makes the convertion throw an exception.
the problem is...if the string is other than numbers ............
Any string value other than numbers will show an error saying INPUT STRING WASN'T IN A CORRECT FORM!!!.
there is a solution for this.....insert your code inside try catch block
try{ your code here}catch(FormatException){}
or find another mechanism to avoid strings other than numbers....
Int32.Parse() will throw an exception if the input value is not an integer. Use Int32.TryParse() to convert a value without throwing an exception. If the conversion fails, TryParse() will return false and zero will be returned:
int intValue = -1;
bool result;
result = Int32.TryParse("23", out intValue); // result = true, intValue = 23
result = Int32.TryParse("AB", out intValue); // result = false, intValue = 0
EDIT: For your specific case, try this:
int tot = 0;
int sum = 0;
int price = 0; // output parameter to receive value
int quantity = 0; // output parameter to receive value
int total = 0; // output parameter to receive value
TryParse(unitprice.Text, out price); // price contains the unit price value
TryParse(quantitytxt.Text out quantity); // quantity contains the quantity value
TryParse(total.Text, out total); // total contains the total value
tot = price * quantity;
sum = total + tot;
total.Text = sum.ToString();
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text+"0") * int.Parse(quantitytxt.Text+"0");
sum = int.Parse(total.Text+"0") + tot;
total.Text = sum.ToString();
Try this code.

Convert int to string?

How can I convert an int datatype into a string datatype in C#?
string myString = myInt.ToString();
string a = i.ToString();
string b = Convert.ToString(i);
string c = string.Format("{0}", i);
string d = $"{i}";
string e = "" + i;
string f = string.Empty + i;
string g = new StringBuilder().Append(i).ToString();
Just in case you want the binary representation and you're still drunk from last night's party:
private static string ByteToString(int value)
{
StringBuilder builder = new StringBuilder(sizeof(byte) * 8);
BitArray[] bitArrays = BitConverter.GetBytes(value).Reverse().Select(b => new BitArray(new []{b})).ToArray();
foreach (bool bit in bitArrays.SelectMany(bitArray => bitArray.Cast<bool>().Reverse()))
{
builder.Append(bit ? '1' : '0');
}
return builder.ToString();
}
Note: Something about not handling endianness very nicely...
If you don't mind sacrificing a bit of memory for speed, you can use below to generate an array with pre-calculated string values:
static void OutputIntegerStringRepresentations()
{
Console.WriteLine("private static string[] integerAsDecimal = new [] {");
for (int i = int.MinValue; i < int.MaxValue; i++)
{
Console.WriteLine("\t\"{0}\",", i);
}
Console.WriteLine("\t\"{0}\"", int.MaxValue);
Console.WriteLine("}");
}
int num = 10;
string str = Convert.ToString(num);
The ToString method of any object is supposed to return a string representation of that object.
int var1 = 2;
string var2 = var1.ToString();
Further on to #Xavier's response, here's a page that does speed comparisons between several different ways to do the conversion from 100 iterations up to 21,474,836 iterations.
It seems pretty much a tie between:
int someInt = 0;
someInt.ToString(); //this was fastest half the time
//and
Convert.ToString(someInt); //this was the fastest the other half the time
string str = intVar.ToString();
In some conditions, you do not have to use ToString()
string str = "hi " + intVar;
or:
string s = Convert.ToString(num);
using System.ComponentModel;
TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
string s = (string)converter.ConvertTo(i, typeof(string));
None of the answers mentioned that the ToString() method can be applied to integer expressions
Debug.Assert((1000*1000).ToString()=="1000000");
even to integer literals
Debug.Assert(256.ToString("X")=="100");
Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...
string s = "" + 2;
and you can do nice things like:
string s = 2 + 2 + "you"
The result will be:
"4 you"
if you're getting from a dataset
string newbranchcode = (Convert.ToInt32(ds.Tables[0].Rows[0]["MAX(BRANCH_CODE)"]) ).ToString();

Convert string to integer

I need help with my code. I would like to write only numbers/integers in my textbox and would like to display that in my listbox.
Is my code below in order? This seems to give an error.
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();
if (newItem == Convert.ToInt32(textBox1.Text))
{
listBox1.Items.Add(newItem);
}
====
Update:
This is how my code looks like now. My question is, can listBox handle the data type "long"? Because when I entered the number 20,000,000 I just got an hour glass for 20 minutes. But when I tried this one with the console, I got the answer. So I'm not sure what kind of element can handle data type "long".
string newItem;
newItem = textBox1.Text.Trim();
Int64 num = 0;
if(Int64.TryParse(textBox1.Text, out num))
{
for (long i = 2; i <= num; i++)
{
//Controls if i is prime or not
if ((i % 2 != 0) || (i == 2))
{
listBox1.Items.Add(i.ToString());
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
int result = int.Parse(textBox1.Text.Trim());
If you want to check for validity:
int result;
if (int.TryParse(textBox1.Text.Trim(), out result)) // it's valid integer...
// int is stored in `result` variable.
else
// not a valid integer
Use this:
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();
Int32 num = 0;
if ( Int32.TryParse(textBox1.Text, out num))
{
listBox1.Items.Add(newItem);
}
else
{
customValidator.IsValid = false;
customValidator.Text = "You have not specified a correct number";
}
This assumes you have a customValidator.
Use int.TryParse() to check if string contains integer value.
textBox1.Text may not contain a valid string representation of an integer (or is just an empty string). To work around that, use Int32.TryParse().
You can do:
Convert.ToInt32(input);
For a longer function using this you can look at:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Basically it checks if the string is null, then it will call int.Parse. This will work under WindowsCE also, which doesn't have int.TryParse.
To be specific as to why your code fails to compile it is because you are comparing a string (newItem) against the result of Convert.ToInt32, which is an integer, which it wont let you do. Also Convert.ToInt32 will raise an exception it the string passed in is not a number.
You can try using int.TryParse, or alternatively write a simple regular expression to validate your input:
int i;
bool isInteger = int.TryParse(textBox1.Text,out i);
or
bool isInteger = System.Text.RegularExpressions.Regex.IsMatch("^\d+$", textBox1.Text);
Are you checking for an empty string?
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();
if(newItem != string.Empty)
{
if ( newItem == Convert.ToInt32(textBox1.Text))
{
listBox1.Items.Add(newItem);
}
}

Categories

Resources