The obvious solution is to use remquo
:
int
roundTo100( double x )
{
int results;
remquo( x, 100.0, &results );
return 100 * results;
}
You'll probably need a fairly recent compiler for this, however:
the function was added to C99, and to C++ with C++11. Depending
on the platform, you might not have it at all, or you might only
have it in <math.h>
(but not in <cmath>
). If the compiler
claims C++11 support, you should have it in <cmath>
. But
don't believe it until you've seen it; no compiler actually
supports C++11 to any real degree yet. On platforms where there
is support for C99 (which would include pretty much all Unix
platforms, and CygWin under Windows), it should be present in
<math.h>
, regardless. (But it is not present in Visual
Studios.)
In the absense of this function, something like:
int
roundTo100( double x )
{
int results = round( x / 100 );
return 100 * results;
}
might do the trick. Beware that the two functions round
slightly differently. The first is rounds up if the remainder
is exactly 50, the second is round to even. The second may
potentially introduce inaccuracies due to the division (or
not—I've not analysed it sufficiently to be sure one way
or the other).
Depending on where your x
comes from, the rounding differences
or the potential inaccuracies may not be an issue. (If, for
example, the x
is derived from some physical measurements with
only 3 decimal digits accuracy, the fact that it may round
"incorrectly" when x
is distant from 50 by some 1E14 or the
like is probably irrelevant.)