51

Possible Duplicate:
Rounding numbers in Objective-C

In Objective-c How to round off Float values?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
ios
  • 6,134
  • 20
  • 71
  • 103

3 Answers3

151

In addition to the other answers:

float theFloat = 1.23456;
int rounded = roundf(theFloat); NSLog(@"%d",rounded);
int roundedUp = ceil(theFloat); NSLog(@"%d",roundedUp);
int roundedDown = floor(theFloat); NSLog(@"%d",roundedDown);
// Note: int can be replaced by float

For rounding to specific decimals, see the question mentioned by Alex Kazaev.

mattsven
  • 22,305
  • 11
  • 68
  • 104
Anne
  • 26,765
  • 9
  • 65
  • 71
  • 1
    You should use `roundf` instead of `lroundf` for casting to `int` without warning. I could not edit your post because of the minimum character change limit for edit. – ersentekin Apr 09 '15 at 13:00
18

The function lroundf() will do it:

float a=20.49;
int myInt = lroundf(a);
Monolo
  • 18,205
  • 17
  • 69
  • 103
Rakesh Bhatt
  • 4,606
  • 3
  • 25
  • 38
  • 1
    what if the value of a is more than 20.5 ? – ios Apr 08 '11 at 11:43
  • 3
    no. lroundf(a) gives u like if value is 20.75 then it become 21 and if value is 20.45 then it become 20... means more than 20.5 then it will become 21 else 20. :) – Rakesh Bhatt Apr 08 '11 at 12:17
1

Convert to int and then convert back to float.

CGFloat *myFloat = 100.765;
NSInteger *myInteger = myFloat;
CGFloat *newFloat = myInteger;

This will work

Dan Hanly
  • 7,829
  • 13
  • 73
  • 134