Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Percentage Calculation always returns 0

I am trying to calculate the percentage of something. It's simple maths. Here is the code.

float percentComplete = 0;
if (todaysCollection>0) {
    percentComplete = ((float)todaysCollection/(float)totalCollectionAvailable)*100;
}

Here the value of todaysCollection is 1751 and totalCollectionAvailable is 4000. Both are int. But percentComplete always shows 0. Why is this happening? Can any one Help me out. I'm new to Objective C.

like image 927
Jason Avatar asked Sep 04 '10 05:09

Jason


3 Answers

But percentComplete always shows 0

How are you displaying percentComplete? Bear in mind it's a float - if you interpret it as an int without casting it you'll get the wrong output. For example, this:

int x = 1750;
int y = 4000;
float result = 0;
if ( x > 0 ) {
    result = ((float)x/(float)y)*100;
}
NSLog(@"[SW] %0.1f", result);   // interpret as a float - correct
NSLog(@"[SW] %i", result);      // interpret as an int without casting - WRONG!
NSLog(@"[SW] %i", (int)result); // interpret as an int with casting - correct

Outputs this:

2010-09-04 09:41:14.966 Test[6619:207] [SW] 43.8
2010-09-04 09:41:14.967 Test[6619:207] [SW] 0
2010-09-04 09:41:14.967 Test[6619:207] [SW] 43

Bear in mind that casting a floating point value to an integer type just discards the stuff after the decimal point - so in my example 43.8 renders as 43. To round the floating point value to the nearest integer use one of the rounding functions from math.h, e.g.:

#import <math.h>

... rest of code here

NSLog(@"[SW] %i", (int)round(result)); // now prints 44
like image 157
Simon Whitaker Avatar answered Sep 21 '22 01:09

Simon Whitaker


Maybe try with *(float)100, sometimes that is the problem ;)

like image 33
cichy Avatar answered Sep 20 '22 01:09

cichy


I think that your value for todaysCollection and totalCollectionAvailable is wrong. Double check for that.

Put the NSLog(@"%d", todaysCollection) right before the if statement

like image 41
vodkhang Avatar answered Sep 21 '22 01:09

vodkhang