-2

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.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
johnnysparks13
  • 31
  • 1
  • 1
  • 4
  • See http://www.tutorialspoint.com/c_standard_library/c_function_floor.htm – PM 77-1 Dec 07 '15 at 00:41
  • "it seems to keep giving me the highest value for all decimal places" - what do you mean by this? – Amadan Dec 07 '15 at 00:41
  • I am storing the values in a float x variable and when i do round(x) , it will just give me the next highest int of all – johnnysparks13 Dec 07 '15 at 00:43
  • 2
    If you have been trying something, the prudent thing to do is post the code for this. It may be the way you're using it. – paddy Dec 07 '15 at 00:45

3 Answers3

3

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.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
2

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).

John3136
  • 28,809
  • 4
  • 51
  • 69
  • Any explanation why `round()` wouldn't work? – juanchopanza Dec 07 '15 at 00:58
  • @juanchopanza No - `round()` should work. I think it used to be to avoid bringing in -lm but I could be wrong - perhaps someone thought it was faster that `round()` – John3136 Dec 07 '15 at 01:08
  • `(int)(some_double + 0.5)` fails for many numbers whose unit-in-last-place is 0.5 or 1. - these may be beyond `INT_MAX`. It also fails for the `double` just less than 0.5. – chux - Reinstate Monica Dec 07 '15 at 01:28
  • OP claims `round()` doesn't work. It is in the question. – juanchopanza Dec 07 '15 at 06:53
  • @juanchopanza OP hasn't provided us enough info to know if/why `round()` doesn't work (short answer: `round()` works, OP's use of it or understanding of it is wrong ;-) – John3136 Dec 07 '15 at 22:56
1

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
  • ...
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084