Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Float Rounding

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"

like image 605
CodeGuy Avatar asked Jan 15 '11 22:01

CodeGuy


2 Answers

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.

like image 126
Jonathan Grynspan Avatar answered Sep 28 '22 23:09

Jonathan Grynspan


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); 
like image 26
Dave Avatar answered Sep 28 '22 23:09

Dave