Round up or down

I have a float that I would 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 do this in Objective-C, so I think I need a standard math function ... Would it not?

+2
source share
5 answers

You can use any of the standard C library math functions defined in math.h. nearbyintfwill work like roundfor ceilfor floorf, depending on what you want.

Xcode ( UNIX) , - .

+8

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

math.h

+4

, . , int (int) (x + 0,5) , , . , round (-1.5) = 2.

+2

, int . 0 <= x < 1. , , , x , x,

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

, x = 0.2, :

1) value = 9.4, 10.

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

2) value = 3.1, 3.

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

x = 0.7, :

3) value = 9.4, 9.

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

4) value = 3.8, 4.

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

, !

0

The way in the old school would be to add 0.5 to the number, and then miss it:

int x = (int) (someFloat + 0.5);
-2
source

All Articles