Cast to int vs floor

Solution 1:

Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.

Solution 2:

As was said before, for positive numbers they are the same, but they differ for negative numbers. The rule is that int rounds towards 0, while floor rounds towards negative infinity.

floor(4.5) = (int)4.5 = 4
floor(-4.5) = -5 
(int)(-4.5) = -4

This being said, there is also a difference in execution time. On my system, I've timed that casting is at least 3 times faster than floor.

I have code that needs the floor operation of a limited range of values, including negative numbers. And it needs to be very efficient, so we use the following function for it:

int int_floor(double x) 
{ 
    return (int)(x+100000) - 100000; 
}

Of course this will fail for very large values of x (you will run into some overflow issues) and for negative values below -100000, etc. But I've clocked it to be at least 3 times faster than floor, which was really critical for our application. Take it with a grain of salt, test it on your system, etc. but it's worth considering IMHO.