How to convert a float to an Int by rounding to the nearest whole integer

Viewed 51357

Is there a way to convert a float to an Int by rounding to the nearest possible whole integer?

5 Answers

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.

How about this:

float f = 1.51;
int i = (int) (f + 0.5);

round() can round a float to nearest int, but it's output is still a float... so cast round()'s output to an integer:

float input = 3.456;
int result;

result = (int)round(input);

//result is: 3

Working example for C++ here.

Related