views:

103

answers:

3

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.

A: 

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

cichy
Most probably not, as only one of the operands has to be a float in order for the expression to evaluate as a float (thanks to implicit casting). That is just my intelligent deduction, though.
BoltClock
Dont know exactly how it looks in obj-c but in C# i had similar problem with that. (float)/(float) can be casted to (int) before *.
cichy
@cichy: float/float is always type float
Mitch Wheat
Yes, i know that float/float is float, but float * int (because in this case 100 is int, not float, 100.0 would be float) may result of int * int. Thats why i recomended casting 100 to type.
cichy
+1  A: 

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

vodkhang
+3  A: 

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
Simon Whitaker