Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculating Percent

Status
Not open for further replies.

hermit22

Programmer
Jul 25, 2001
11
US
Before I begin, I apologize if this is something stupid on my part, or it's a question that's already been answered.

Basically, I need to calculate the percentage of 1 data set to another. So I have this:

Code:
int percentage = 0;
DataRow r = dsLocal.Tables[0].Rows[0];
int curr_count = System.Convert.ToInt32(r[0]);
if (curr_count > 0)
  {percentage = (curr_count % total);}
else
  {percentage = 0; }

When I run it, my messagebox output:

Code:
MessageBox.Show(percentage.ToString(+" "+curr_count.ToString()+ "/"+total.ToString());

shows that the percentage is only assigned curr_count. So, in the first example, I have:

curr_count = 159
total = 297
percentage = 159

although percentage should equal 53. Any ideas?
 
The following statement
{percentage = (curr_count % total);}
calcualte the modulo between curr_count and total and never a percentage e.g. which percent is curr_count from the total!
The m%n operation calculates the rest when you divide m by n.
Example: 10 %2 --> 0
23 % 2 --> 1
Generally if m, n are positive integers then m%n is the r number that satisfy the egality:
m = q * n + r
Always : 0<=r< n

In your case : 159% 297 is 159 !
Why ?
159 = 0 * 297 + 159

In order to calculate the right percentage do:
if (total > 0)
percentage = 100* curr_count / total
else ...

-obislavu-


 
Like obislavu says -

The Percent operator (%) is the modulus operator. In order to calculate a percentage you need to divide one by the other, then multiply by 100.

Note that he is doing the multiplication first. This is because he's using integer variables, and if you did the division first you'd get 0 or 1 as a result when the results are truncated to fit the int result variable.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top