Subtract (-) 2 Text Labels from each other to get result - c#

Well, I've tried it with ToInt, ToString, and I'm out of options.
I'm trying to substract 2 Label Texts from each other. (Those contains numbers from RSS)
What I have at the moment:
lblOldID.Text = nodeChannel["oldid"].InnerText;
lblNewID.Text = nodeChannel["newid"].InnerText;
So let's say oldid contains "500" and newid "530".
But for some reason, I can't substract (-) them.
What I want:
lblResultID.Text = lblOldID.Text - lblNewID.Text;
Example: Result = 530 - 500
So how is that possible?

You need to convert the text to ints.
//These are the ints we are going to perform the calculation on
Int32 oldID = 0;
Int32 newID = 0;
//TryParse returns a bool if the string was converted to an int successfully
bool first = Int32.TryParse(lblOldID.Text, out oldID);
bool second = Int32.TryParse(lblNewID.Text, out newID);
//Check both were converted successfully and perform the calculation
if(first == true && second == true)
{
lblResultID.Text = (oldID - newID).ToString();
}
else
{
lblResultID.Text = "Could not convert to integers";
}
TryParse prevents an exception being thrown if the data in the labels cannot be converted to integers. Instead, it returns false (or true if the numbers were parsed successfully).

If you want the label text to be, literally, 530 - 500, concatenate the strings like so:
lblResultID.Text = lblOldID.Text + " - " + lblNewID.Text;
If you want the label text to be the result of subtracting the numbers represented in the labels, convert them to integers first:
int old = Int32.Parse(lblOldID.Text);
int new = Int32.Parse(lblNewID.Text);
lblResultID.Text = (old - new).ToString();
(You'll need some error checking in there if there's the possibility that either value might not convert cleanly to an integer)

Perhaps because you really should parse them:
lblResultID.Text = (int.Parse(lblOldID.Text) - int.Parse(lblNewID.Text)).ToString();
Or in string format:
lblResultID.Text = lblOldID.Text + " - "+ lblNewID.Text;

Related

All indexes of string-array return null

I've been coding in C# (winforms) for a project for 2 weeks now. My goal is to build a GUI for an FFT-Analysis (frequency-realm).
my Problem:
I keep running into the same problem: i receive 1024 int values (one blocksize) separated by white spaces in one string via serial port and then terminated by \n into a buffer uart_buf. To obtain numeric values, i use uart_buf.split(' ') into a string[] parse_buf and then try to access a single value in ASCII-format like this: parse_buf[i] = val_buf. This i then try to form into a numeric via value = int.Parse(val_buf), without success: System.ArgumentNullException: value cant be NULL.
What I've tried:
value = int.Parse(parse_buf[i]); This returns a format exception
printing parse_buf[i] to a textbox shows an expected value (the received data is correct)
observing the main buffer uart_buf shows valid data like this: "41 30 2 0 0 0 0 0 0 0 3 40 500 69..."
starting from index 1 (or any other) instead of 0 changes nothing
What I don't get:
A single element (ergo a string) of parse_buf contains a value in text-form, e.g. "41". I want to save it to a regular string val_buf, which i should be able to parse to int. Why is every string accessed via parse_buf[i] null?
Code-Fragments:
private void displayData(object o, EventArgs e)
{
parse_buf = uart_buf.Split(' ');
tb_data.Text = parse_buf[0]; //this shows valid data in a tb
for (i = 1; i < parse_buf.Length; i++) //about 1024 loops
{
//problem area:
parse_buf[i] = val_buf;
fft = int.Parse(val_buf);
//ignore this:
f = i * 20;
chart1.Series[0].Points.AddXY(f, fft);
}
}
I usually work in C with embeded systems, so sorry for not seeing the problem instantly. Thanks.
private void DisplayData(object o, EventArgs e)
{
parse_buf = uart_buf.Split(' ');
tb_data.Text = parse_buf[0]; //this shows valid data in a tb
for (i = 0; i < parse_buf.Length; i++) //about 1024 loops
{
//problem area:
int.TryParse(parse_buf[i], out ftt);
//ignore this:
chart1.Series[0].Points.AddXY(i * 20, fft);
}
}

How to format numbers in scientific notation with powers in superscript

I need to write values like:
9.6 x 10²
9.6 x 10¹²
I need to know if there is a way to format numbers as above in a string.
You have to find the appropriate character from the code page you are using, for example UTF-8:
string superScript2 = "²";
There is no such thing as formatting in a string, it is just all data.
Try this:
public static string Eng(this double x, string format="g")
{
const string sup_signs = "⁺⁻⁼⁽⁾ⁿ";
const string sup_digits = "⁰¹²³⁴⁵⁶⁷⁸⁹";
if(double.IsNaN(x) || double.IsInfinity(x))
{
return x.ToString();
}
int num_sign = Math.Sign(x);
x = Math.Abs(x);
// group exponents in multiples of 3 (thousands)
int exp = (int)Math.Floor(Math.Log(x, 10)/3)*3;
// otherwise use:
// int exp = (int)Math.Floor(Math.Log(x, 10));
// and handle the exp==1 case separetly to avoid 10¹
x*= Math.Pow(10, -exp);
int exp_sign = Math.Sign(exp);
exp = Math.Abs(exp);
// Build the exponent string 'dig' from right to left
string dig = string.Empty;
while(exp>0)
{
int n = exp%10;
dig = sup_digits[n] + dig;
exp = exp/10;
}
// if has exponent and its negative prepend the superscript minus sign
if(dig.Length>0 && exp_sign<0)
{
dig = sup_signs[1] + dig;
}
// prepend answer with minus if number is negative
string sig = num_sign<0 ? "-" : "";
if(dig.Length>0)
{
// has exponent
return $"{sig}{x.ToString(format)}×10{dig}";
}
else
{
// no exponent
return $"{sig}{x.ToString(format)}";
}
}
As a test case run
static void Main(string[] args)
{
// Type code here.
double x = Math.PI/50e5;
for(int i = 0; i < 20; i++)
{
// Format output to 12 wide column, right aligned
Debug.WriteLine($"{ Eng(x, "g4"),12}");
x*=50;
}
}
with the output:
628.3×10⁻⁹
31.42×10⁻⁶
1.571×10⁻³
78.54×10⁻³
3.927
196.3
9.817×10³
490.9×10³
24.54×10⁶
1.227×10⁹
61.36×10⁹
3.068×10¹²
153.4×10¹²
7.67×10¹⁵
383.5×10¹⁵
19.17×10¹⁸
958.7×10¹⁸
47.94×10²¹
2.397×10²⁴
119.8×10²⁴
By no means optimized, but it does the job. The exponents are in engineering form (multiples of 3 only, in order to avoid things like 10¹). As a bonus, the number can be formatted to a specific number of significant digits by supplying a format code like g4 or g5 for 4 or 5 digits respectively.
It can handle negative or positive numbers
It can handle negative or positive exponents of 10
In can format the mantissa
It can handle NAN or Inf.
It's in extension form for re-usability
As a follow up to my comment above - does something like this do what you require :
public String FormatAs10Power(decimal val)
{
string SuperscriptDigits = "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";
string expstr = String.Format("{0:0.#E0}", val);
var numparts = expstr.Split('E');
char[] powerchars = numparts[1].ToArray();
for (int i = 0; i < powerchars.Length; i++)
{
powerchars[i] = (powerchars[i] == '-') ? '\u207b' : SuperscriptDigits[powerchars[i] - '0'];
}
numparts[1] = new String(powerchars);
return String.Join(" x 10",numparts);
}
See : https://dotnetfiddle.net/dX7LAF
As per my comment above - the number is first converted to an exponential format string (https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#EFormatString), that string is then split on the exponential separator 'E'. The first array is the numeric part, the second the power of 10 to which it is raised - this is converted to superscript characters using one of the techniques of the link I gave (Convert a string/integer to superscript in C#), converted back to a string & the two parts combined using "x 10" as the new separator.
I have assumed you want the value to single digit precision as per your example with no preceding + sign. If you need anything else you could pass the format as a parameter. The code for superscript + is '\u207A'. There is a link here (at the time of writing) giving the list of superscript codes : http://unicode.org/charts/PDF/U2070.pdf

How to take digits from two different numbers and form a new one

I have the following problem here:My input is several lines of 2 digit numbers and I need to make a new number using the second digit of the first number and the first of the next one.
Example:
int linesOfNumbers = Convert.ToInt32(Console.ReadLine());
for(int i = 0,i<linesOfNumbers,i++)
{
int numbers = Conver.ToInt32(Console.ReadLine());
//that's for reading the input
}
I know how to separate the numbers into digits.My question is how to merge them.
For example if your input is 12 and 21 the output should be 22.
I like oRole's answer, but I think they're missing a couple things with the example input that you provided in your comment. I'll also point out some of the errors in the code that you have.
First off, if you're only given the input 12,23,34,45, then you don't need to call Console.ReadLine within your for loop. You've already gotten the input, you don't need to get any more (from what you've described).
Secondly, unless you're doing mathematical operations, there is no need to store numerical data as ints, keep it as a string, especially in this case. (What I mean is that you don't store Zip Codes in a database as a number, you store it as a string.)
Now, onto the code. You had the right way to get your data:
var listOfNumbers = Console.ReadLine();
At that point, listOfNumbers is equal to "12,23,34,45". If you iterate on that variable as a string, you'll be taking each individual character, including the commas. To get each of the numbers to operate on, you'll need to use string.Split.
var numbers = listOfNumbers.Split(',');
This turns that list into four different two character numbers (in string form). Now, you can iterate over them, but you don't need to worry about converting them to numbers as you're operating on the characters in each string. Also, you'll need a results collection to put everything into.
var results = new List<string>();
// Instead of the regular "i < numbers.Length", we want to skip the last.
for (var i = 0; i < numbers.Length - 1; i++)
{
var first = numbers[i];
var second = numbers[i + 1]; // This is why we skip the last.
results.Add(first[1] + second[0]);
}
Now your results is a collection of the numbers "22", "33", and "44". To get those back into a single string, you can use the helper method string.Join.
Console.WriteLine(string.Join(",", results));
You could use the string-method .Substring(..) to achieve what you want.
If you want to keep int-conversion in combination with user input, you could do:
int numA = 23;
int numB = 34;
int resultAB = Convert.ToInt16(numA.ToString().Substring(1, 1) + numB.ToString().Substring(0, 1));
Another option would be to take the users input as string values and to convert them afterwards like that:
string numC = "12";
string numD = "21";
int resultCD = Convert.ToInt16(numC.Substring(1, 1) + numD.Substring(0, 1));
I hope this code snippet will help you combining your numbers. The modulo operator (%) means: 53 / 10 = 5 Rest 3
This example shows the computation of the numbers 34 and 12
int firstNumber = 34 - (34 % 10) // firstNumber = 30
int secondNumber = 12 % 10; // secondNumber = 2
int combined = firstNumber + secondNumber; // combined = 32
EDIT (added reading and ouput code):
boolean reading = true;
List<int> numbers = new ArrayList();
while(reading)
{
try
{
int number = Convert.ToInt32(Console.ReadLine());
if (number > 9 && number < 100) numbers.Add(number);
else reading = false; // leave reading process if no 2-digit-number
}
catch (Exception ex)
{
// leave reading process by typing a character instead of a number;
reading = false;
}
}
if (numbers.Count() > 1)
{
List<int> combined = new ArrayList();
for (int i = 1; i <= numbers.Count(); i++)
{
combined.Add((numbers[i-1] % 10) + (numbers[i] - (numbers[i] % 10)));
}
//Logging output:
foreach (int combination in combined) Console.WriteLine(combination);
}
As you mention, if you already have both numbers, and they are always valid two digit integers, following code should work for you.
var num1 = 12;
var num2 = 22;
var result = (num2 / 10)*10 + (num1 % 10);
num2/10 returns the first digit of second number, and num1 % 10 returns the second digit of the first number.
The % and / signs are your savior.
If you want the 'ones' digit of a number (lets call it X), simply do X%10 - the remainder will be whatever number is in the 'ones' digit. (23%10=3)
If, instead, the number is two digits and you want the 'tens' digit, divide it by ten. (19/10=1).
To merge them, multiply the number you want to be in the 'tens' digit by ten, and add the other number to it (2*10+2=22)
There are other solutions like substring, etc and many one have already given it above. I am giving the solution VIA LINQ, note that this isn't efficient and it's recommended only for learning purpose here
int numA = 12;
int numB = 21 ;
string secondPartofNumA = numA.ToString().Select(q => new string(q,1)).ToArray()[1]; // first digit
string firstPartofNumB = numB.ToString().Select(q => new string(q,1)).ToArray()[0]; // second digit
string resultAsString = secondPartofNumA + firstPartofNumB;
int resultAsInt = Convert.ToInt32(resultAsString);
Console.WriteLine(resultAsString);
Console.WriteLine(resultAsInt);

Adding Numbers in C#

I currently have this, but it keeps resulting in the number say I put in 5 it will make it 51 instead of the result I want of 6. Can anyone help me?
int number;
int outcome;
number = int.Parse(numberInputTextBox.Text);
outcomeLabel.Text = number + 1 .ToString();
number = int.Parse(numberInputTextBox.Text);
outcomeLabel.Text = (number + 1).ToString();
You forgot to add ( ). Your sample was:
1) take 1 and convert to string
2) add number and string
in point 2) the number was casted to string before adding to second string. That's why you got string concatenation "5"+"1"="51" instead of integer sum 5+1=6
1.ToString() will return a string, which you are then adding the string "5" to, as C# will
implicitly cast the number 5 to the string "5" when trying to add it to a string.
You need to first add one, then convert to a string, giving something like this:
outcomeLabel.Text = (number + 1).ToString();
or
int newNumber = number + 1;
outcomeLabel.Text = newNumber.ToString();
Just add parentheses...
number = int.Parse(numberInputTextBox.Text);
outcomeLabel.Text = (number + 1).ToString();

C# WebForm - Add averages of student marks, print result in the web form, then store it in the database

protected void btnView_Click(object sender, EventArgs e)
{
int StudentAdmissionNo = Convert.ToInt32(txtAdmissionNo.Text);
string StudentName = txtStudentName.Text;
DateTime DateOfBirth = Convert.ToDateTime(txtDOB.Text);
string Gender = txtGender.Text;
string Standard = txtstandard.Text;
string Section = txtSection.Text;
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
//int Total = Convert.ToInt32(lblTot.Text);
//double Average = Convert.ToDouble(lblAve.Text);
string Result = lblRes.Text;
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); //This also gives an error
}
In this code I have an error coming from lblTot = to add marks and it coming like same to printing that numbers what I entered and average also not working.
You are concatenating the Text. When you use + with text/string it acts as a concatenation operator.
You need to convert text to Integer for arithmatic operations first.
Use Convert.ToInt32(input);
Replacing your code with the below lines should fix it.
lblTot.Text = (Convert.ToInt32(txtTelugu.Text) + Convert.ToInt32(txtEnglish.Text) + Convert.ToInt32(txtMathematics.Text)).ToString();
lblAve.Text = ((Convert.ToInt32(lblTot.Text)) / 3.00).ToString();
Update
I just noticed that you have already assigned the required values to integers here:
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
Which is correct, you just needed to add these variables, like:
int total = Telugu + English + Mathematics;
lblTot.Text = total.ToString();
And then, for average just use the total variable that we just assigned the value to:
lblAve.Text = Convert.ToString(Convert.ToDouble(total / 3.00)); // convert the average to double as you may get values with decimal point. And then convert it back to string in order to assign it to a Label control.
If my assumption of what you're trying to do is correct your code should look like this.
decimal total = Teluga + English + Mathematics;
decimal average = (Teluga + English + Mathematics) / 3.00;
lblTot.Text = total.ToString();
lblAve.Text = average.ToString();
You are trying to use strings to perform mathematical operations and that won't work.
Also, typically
int x = Int32.TryParse(txtEnglish.Text)
is a better way to turn string into integers
The root of both your problems is that a textbox.Text property is a string.
In your first problem, you are concatenating strings, which is why it's giving you you 456565.
In your second problem, you are trying to perform arithmetic on a string and a number.
Cast your strings as numbers by declaring an Int32 variable placeholder and using the TryParse method on your string, like so:
Int32 txtTeluguResult;
Int32.TryParse(txtTelugu.Text, txtTeluguResult);
Also note that TryParse will put 0 in for your result variable if it cannot successfully parse the text input. You may wish to use Convert.ToInt32() instead, which throws a FormatException if it fails, depending on what behavior you want.
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); this also giving error?
you are using string variables not int or real or decimal
do something like
lblTot.Text = (((int)txtTelugu.Text + (int)txtEnglish.Text + (int)txtMathematics.Text)).ToString();
lblAve.Text = (((int)(lblTot.Text) / 3.00)).ToString(); this also giving error?

Categories