Streetboy
Streetboy

Reputation: 4401

Convert float to int in Objective-C

How can I convert a float to int while rounding up to the next integer? For example, 1.00001 would go to 2 and 1.9999 would go to 2.

Upvotes: 11

Views: 29390

Answers (4)

mitul mandanka
mitul mandanka

Reputation: 1

if we have float value like 13.123 to convert it into integer like 13

Code

float floatnumber=13.123; //you can also use CGFloat instead of float

NSLog(@"%.f",floatnumber); // use for print in command prompt  

Upvotes: 0

iOS dev
iOS dev

Reputation: 2284

float myFloat = 3.333

// for nearest integer rounded up (3.333 -> 4):
int result = (int)ceilf(myFloat );

// for nearest integer (3.4999 -> 3, 3.5 -> 4):
int result = (int)roundf(myFloat );

// for nearest integer rounded down (3.999 -> 3):
int result = (int)floor(myFloat);

// For just an integer value (for which you don't care about accuracy) 
int result = (int)myFloat;

Upvotes: 65

Suhail Bhat
Suhail Bhat

Reputation: 453

You can use following C methods to get the int values from different dataTypes.

extern float ceilf(float);
extern double ceil(double);
extern long double ceill(long double);

These functions return float, double and long double respectively. But the job of these function is to get ceil of or floor of the argument. As in http://en.wikipedia.org/wiki/Floor_and_ceiling_functions

Then you can cast the return value to desired type like.

int intVariable = (int)ceilf(floatValueToConvert);

Hope it is helpful.

Upvotes: 1

Vladimir
Vladimir

Reputation: 170819

Use ceil function:

int intValue = (int)ceil(yourValue);

Upvotes: 11

Related Questions