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.
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
Maybe try with *(float)100, sometimes that is the problem ;)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With