The Superstition of Adding 0.5 Then Casting to int for Rounding a Float Value
When looking at other people’s code, occasionally you come across this kind of code for rounding:
float f;
// ...
int r = static_cast<int>(f + 0.5f);
This approach is often found in books and is not necessarily incorrect for specific use cases.
I used to use this “trick” myself in the past.
However, I believe that this code should not be written in general.
Firstly, this code does not work correctly when f
is negative:
float f = -1.1f;
// ...
int r = static_cast<int>(f + 0.5f); // r = 0
In C++, you can simply #include <cmath>
and use std::nearbyint()
instead:
float f = -1.1f;
// ...
int r = std::nearbyint(f); // r = -1
Depending on your needs, you can also use std::rint()
or std::round()
.
In most programming languages, similar functions should be available.
By using these functions, your intentions become clear, and the risk of introducing unnecessary bugs is eliminated.
Therefore, I encourage people to use these functions actively.