Calculating a percent in a c# web app

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I can not figure out what I'm doing wrong. I'm trying to calc a percent by
dividing a small number by a large number, but result always = 0.

This is what I have.

double nbr1
double nbr2
int pct

nbr1 = 180
nbr2 = 500

pct = (nbr1 / nbr2) * 100

The pct always = 0 and it should be 36. Can anyone tell me what I'm doing
wrong.

Thanks in advance.

--
 
Hi,

The code you presented will not compile, if you fix the compile errors I am
100% you will get the expected results.

double nbr1;
double nbr2;
int pct;

nbr1 = 180;
nbr2 = 500;

pct = (int)((nbr1 / nbr2) * 100);

I am going to go out on a limb here and guess that you missed the extra
parens when casting, for instance
pct = (int)(nbr1 / nbr2) * 100; // Note the missing parens here

This will result in an answer of 0 since the division is first cast to
integer effectively truncating 0.36 to 0 and then multiplied by 100.

Hope this helps
 
I think if you make the change below it should work.

pct = (int)((nbr1 / nbr2) * 100.0);
 
Back
Top