Does casting to an int after std::floor guarantee the right result?

Jesse Beder picture Jesse Beder · Mar 3, 2009 · Viewed 23.8k times · Source

I'd like a floor function with the syntax

int floor(double x);

but std::floor returns a double. Is

static_cast <int> (std::floor(x));

guaranteed to give me the correct integer, or could I have an off-by-one problem? It seems to work, but I'd like to know for sure.

For bonus points, why the heck does std::floor return a double in the first place?

Answer

Jon Skeet picture Jon Skeet · Mar 3, 2009

The range of double is way greater than the range of 32 or 64 bit integers, which is why std::floor returns a double. Casting to int should be fine so long as it's within the appropriate range - but be aware that a double can't represent all 64 bit integers exactly, so you may also end up with errors when you go beyond the point at which the accuracy of double is such that the difference between two consecutive doubles is greater than 1.