say i have:
55.3 and want 55
55.6 and want 56
81.1 and want 81
etc.
i have been trying to use the round()
function but it seems to keep giving me the highest value for all decimal places.
say i have:
55.3 and want 55
55.6 and want 56
81.1 and want 81
etc.
i have been trying to use the round()
function but it seems to keep giving me the highest value for all decimal places.
OP has not posted code that failed. Certain OP coded incorrectly.
Using round()
is the correct way to round a double
before converting to an int
. Of course it must be in range.
#include <math.h>
#include <assert.h>
int round_to_int(double x) {
x = round(x);
assert(x >= INT_MIN);
assert(x < (INT_MAX/2 + 1)*2.0);
return (int) x;
}
See How to test for lossless double / integer conversion? for details about the assert()
s.
Why not use (int)(x + 0.5);
?
1) It fails for negative numbers.
2) It can fail for the double
just smaller than 0.5
as the x + 0.5
can round to 1.0
.
3) When the precision of int
exceeds double
, values where the least significant bit is 0.5 or 1.0, x+0.5
may round to the next integer.
4) Unadorned, it has no range checking.
In the olden days we used to say int the_int = (int)(some_double + 0.5);
(obviously beware if you are dealing with negative values too).
Increase the magnitude by one half and truncate:
int round_up_or_down(double x)
{
return x > 0 ? x + 0.5 : x - 0.5;
}
This distributes the real intervals uniformly:
[-1.5, -0.5) => -1
[-0.5, +0.5) => 0
[+0.5, +1.5) -> +1