tags:

views:

361

answers:

3

is there a way to convert a float to an Int by rounding to nearest whole integer?

cheers

Sam

+3  A: 

How about this:

float f = 1.51;
int i = (int) (f + 0.5);
Paul Beckingham
it works. But, how? shouldnt the int be 2.01? then how does the int go down?
Sam Jarman
An integer is by definition a whole number, so how can it possibly have any fractional value?
Quick Joe Smith
well if thats true, then shouldn't i = f ;just work?
Sam Jarman
Doesn't work for negative numbers, see ergosys for correct answer.
BlueRaja - Danny Pflughoeft
+3  A: 

Actually Paul Beckingham's answer isn't quite correct. If you try a negative number like -1.51, you get -1 instead of -2.

The functions round(), roundf(), lround(), and lroundf() from math.h work for negative numbers too.

ergosys
ah yes, I see. however, in my app negative numbers are not used. for next time, could you give me an example of those fuctions please?
Sam Jarman
Aboslutely - thanks for pointing that out.
Paul Beckingham
Rounding is one of those things you can get into arguments with others for hours. There's also a school of thought that says the "add a half and drop the fractional part" biases the outputs upward (because `k + 0` doesn't change and `k + 0.5` always goes up for a given integer `k`), so they recommend rounding even halves down and odd halves up (i.e. `k + 0.5` rounds to `k` for `k` = ..., -4, -2, 0, 2, 4, ... and it rounds to `k + 1` for `k` = ..., -3, -1, 1, 3, ...). Basically, the naive way can throw statistics off.
Mike DeSimone
A: 

(int)floor(f+0.5);

marichyasana