As strange as it may seems, I can't find how to cleanly convert a float
to an int
.
This technique
int int_value = (int)(float_value + 0.5);
triggers a
warning: use of old-style cast
in gcc.
So, what is the modern-style, simple way to convert a float
to an int
? (I accept the loss of precision of course)
As Josh pointed out in the comments, + 0.5
is not very reliable. For extra security you could combine a static_cast
with std::round
like so:
int int_value = static_cast<int>(std::round(float_value));
For the casting part, see this excellent post for an explanation.
try:
int int_value = static_cast<int>(float_value + 0.5);
FYI: different casts in C++ gave a very good explanation about those 4 casts introduced in C++.
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