Reputation: 83
I would like to understand why
double nbr = 102262.5;
boost::format("%.0f") % nbr;
gives 102262
while round(102262.5)
gives 102263.0
If we take another example value 34087.5
boost::format("%.0f") % nbr
gives 34088
and round(34087.5)
gives the same 34088
Does it mean round implements a more sophisticated algorithm to ensure the nearest while format or printf does not?
Upvotes: 4
Views: 410
Reputation: 185
BTW, if you want round half to even behavior in C++ without relying on Boost, you could call the C++ standard library function std::rint
which is available if your compiler supports C++11 (or later) C++ standard.
If you're using a pre-C++11 compiler which supports calling C standard library functions, you could call one of the C standard library functions rintf
, rint
, or rintl
, depending on which floating-point type you are using.
Upvotes: 1
Reputation: 6105
There is a thing called "round half to even" or "round half to odd" (link).
This is a rule to reduce the bias of rounding errors and
boost::format
seems to implement such a strategy.
Essentially this is to round the tie-breaking cases (such as 1.5 or 2.5) up and down equally often in a deterministic way (depending on the number itself). If one would always round up or round down these cases all, a statistical bias could be introduced by rounding.
The latter is the more "classical" way of rounding which seems to be implemented by round
.
Note that the strategy implemented by boost::format
(round half to even) corresponds to the default rounding mode in the IEEE 754 standard.
Upvotes: 8