Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three textboxes that do calculations on a textbox text change. When the calculations is done there is a negative in the answer. Here is my code:

C#
int k = Convert.ToInt32(TextBox1.Text);
int l = Convert.ToInt32(TextBox2.Text.Replace(",", ""));
TextBox3.Text = Convert.ToString((k - l) * 100.0 / ((k + l) / 2));
TextBox3.Text = Math.Round(Convert.ToDouble(TextBox3.Text), 2).ToString();


Here is what I am trying to do.

HTML
Calculate percentage difference
between V1 = 100 and V2 = 1000

( | V1 - V2 | / ((V1 + V2)/2) ) * 100

= ( | 100 - 1000 | / ((100 + 1000)/2) ) * 100
= ( | -900 | / (1100/2) ) * 100
= ( 900 / 550 ) * 100
= 1.636364 * 100

= 163.6364% difference 

It is from this website:

<a href="http://www.calculatorsoup.com/calculators/algebra/percent-difference-calculator.php">http://www.calculatorsoup.com/calculators/algebra/percent-difference-calculator.php</a>[<a href="http://www.calculatorsoup.com/calculators/algebra/percent-difference-calculator.php" target="_blank" title="New Window">^</a>]

How will I get the negative out?
Posted

1 solution

When you see the formula:
Percent difference = ( | ΔV |/ ( ∑V/2) ) * 100 = ( | (V1 - V2) | / ((V1 + V2)/2) ) * 100

You know you must use the absolute value (http://en.wikipedia.org/wiki/Absolute_value[^]) of the difference V1-V2 thus:

TextBox3.Text = Convert.ToString((Math.Abs(k - l)) * 100.0 / ((k + l) / 2));


This will make the difference always non-negative.

To round:
TextBox3.Text = Convert.ToString(Math.Round((Math.Abs(k - l)) * 100.0 / ((k + l) / 2)));
 
Share this answer
 
v3
Comments
Computer Wiz99 20-Oct-14 22:39pm    
pwasser, Thanks for the code. I have one more question. How do I round to the whole number to get rid of the decimal and the numbers after that?
[no name] 20-Oct-14 22:49pm    
Have edited.
Computer Wiz99 20-Oct-14 23:05pm    
I already do rounding. Look at my code for the rounding.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900