How to round an float value and convert it into NSInteger value in the iPhone SDK?
I need to round a float value and convert it into an NSInteger
value.
For example:
float f = 90.909088;
I want the 开发者_如何学运维result to be 91. How to get rid of this?
A quick round and cast will work for negative values as well as positives:
NSInteger intValue = (NSInteger) roundf(f);
One of the following C math functions might work for you:
- double ceil(double)
- double floor(double)
- double nearbyint(double)
- double rint(double)
- double round(double)
- long int lrint(double)
- long int lround(double)
- long long int llrint(double)
- long long int llround(double)
- double trunc(double)
To get more documentation, open a terminal session and type (for example)
man lround
I pick lround as an example because I think that is the one you want.
Do
f = floor(f + 0.5)
before the integer conversion.
Try:
float f = 90.909088;
NSNumber *myNumber = [NSNumber numberWithDouble:(f+0.5)];
NSInteger myInt = [myNumber intValue];
精彩评论