开发者

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开发者_如何学Go...

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


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.


use

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

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


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.


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!


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜