How might I round a float to the nearest integer in Objective-C:
Example:
float f = 45.698f; int rounded = _______; NSLog(@"the rounded float is %i",rounded);
should print "the rounded float is 46"
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);
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