Objective-C Float Rounding
Use the C standard function family round()
. roundf()
for float
, round()
for double
, and roundl()
for long double
. You can then cast the result to the integer type of your choice.
The recommended way is in this answer: https://stackoverflow.com/a/4702539/308315
Original answer:
cast it to an int after adding 0.5.
So
NSLog (@"the rounded float is %i", (int) (f + 0.5));
Edit: the way you asked for:
int rounded = (f + 0.5);NSLog (@"the rounded float is %i", rounded);
For round float
to nearest integer use roundf()
roundf(3.2) // 3roundf(3.6) // 4
You can also use ceil()
function for always get upper value from float
.
ceil(3.2) // 4ceil(3.6) // 4
And for lowest value floor()
floorf(3.2) //3floorf(3.6) //3