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?
Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.
std::floor is meant to return an integer, and the cast is specified in terms of an integer value.
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.
static_cast <int> (std::floor(x));
does pretty much what you want, yes. It gives you the nearest integer, rounded towards -infinity. At least as long as your input is in the range representable by ints. I'm not sure what you mean by 'adding .5 and whatnot, but it won't have the same effect
And std::floor returns a double because that's the most general. Sometimes you might want to round off a float or double, but preserve the type. That is, round 1.3f to 1.0f, rather than to 1.
That'd be hard to do if std::floor returned an int. (or at least you'd have an extra unnecessary cast in there slowing things down).
If floor only performs the rounding itself, without changing the type, you can cast that to int if/when you need to.
Another reason is that the range of doubles is far greater than that of ints. It may not be possible to round all doubles to ints.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With