2

I have a float which I'd like to round up or down to the nearest integer.

For example:

1.4 = 1.0 1.77 = 2.0 1.1 = 1.0

etc...

I'm doing this in Objective C, so I guess I need a standard math function... Would nearbyintf do it?

nykash
  • 447
  • 5
  • 16
mootymoots
  • 4,545
  • 9
  • 46
  • 74
  • possible duplicate of [Objective-C Float Rounding](http://stackoverflow.com/questions/4702408/objective-c-float-rounding) or [How to round off float values?](http://stackoverflow.com/questions/5594116/objective-c-how-to-round-off-float-values) – jscs Aug 21 '11 at 20:07
  • @andrewx I downvoted your answer, for reasons I explained in the comment. Whether or not it is "taught in many books", your recommendation to rely on casting is poor advice. – benzado Mar 02 '12 at 11:10

5 Answers5

8

You can use any of the standard C library math functions defined in math.h. nearbyintf would work, as would roundf or ceilf or floorf, depending on what you want.

Xcode will show you the documentation (UNIX manual page) for these functions if you option-double-click them in the editor.

benzado
  • 82,288
  • 22
  • 110
  • 138
4

use

double a = 2.3;
double b = round(a);

You can find round and other math functions in math.h

mjisrawi
  • 7,846
  • 3
  • 24
  • 27
2

Whenever rounding, consider whether negative numbers are possible. If so, the traditional int (int) (x + 0.5) may not do what you want and the round function may be better. For example, round (-1.5) = 2.

mackworth
  • 5,873
  • 2
  • 29
  • 49
0

Rounding is very easy to implement, as casting a value as an int truncates the decimal part of the number. Let 0 <= x < 1. Then if you want all values to round down to the nearest integer if the decimal part is less than x, and round up to the nearest integer if the decimal part is greater than or equal to x, then you need only calculate:

int roundedValueBasedOnX = (int) (value + (1 - x));

As an example, if x = 0.2, then we have:

1) value = 9.4, should round to 10.

int roundedValueBasedOnX = (int) (9.4 + (1 - 0.2)) = (int) (9.4 + 0.8) = (int) (10.2) = 10;

2) value = 3.1, should round to 3.

int roundedValueBasedOnX = (int) (3.1 + (1 - 0.2)) = (int) (3.1 + 0.8) = (int) (3.9) = 3;

If x = 0.7, then we have:

3) value = 9.4, should round to 9.

int roundedValueBasedOnX = (int) (9.4 + (1 - 0.7)) = (int) (9.4 + 0.3) = (int) (9.7) = 9;

4) value = 3.8, should round to 4.

int roundedValueBasedOnX = (int) (3.8 + (1 - 0.7)) = (int) (3.8 + 0.3) = (int) (4.1) = 4;

Hope that helps!

msgambel
  • 7,320
  • 4
  • 46
  • 62
-2

The old-school way would be to add 0.5 to the number and then let it truncate:

int x = (int) (someFloat + 0.5);
EricS
  • 9,650
  • 2
  • 38
  • 34
  • Your solution doesn't take into account negative numbers (and if it did, you'd basically be rewriting the `roundf` function). – benzado Mar 01 '12 at 22:39