mootymoots
mootymoots

Reputation: 4575

Round up or down

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?

Upvotes: 2

Views: 8815

Answers (5)

mackworth
mackworth

Reputation: 5953

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.

Upvotes: 2

msgambel
msgambel

Reputation: 7340

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!

Upvotes: 0

EricS
EricS

Reputation: 9768

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

int x = (int) (someFloat + 0.5);

Upvotes: -2

mjisrawi
mjisrawi

Reputation: 7936

use

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

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

Upvotes: 4

benzado
benzado

Reputation: 84338

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.

Upvotes: 8

Related Questions