65

Once in a while, I find myself rounding some numbers, and I always have to cast the result to an integer:

int rounded = (int) floor(value);

Why do all rounding functions (ceil(), floor()) return a floating number, and not an integer? I find this pretty non-intuitive, and would love to have some explanations!

Yamaneko
  • 3,433
  • 2
  • 38
  • 57
Wookai
  • 20,883
  • 16
  • 73
  • 86
  • Good question - I had never thought to ask that – Martin Beckett Aug 10 '09 at 20:42
  • 4
    This duplicate managed to acquire an answer that is (IMHO) better: http://stackoverflow.com/questions/15348180/why-doesnt-floor-return-an-integer – Omnifarious Mar 11 '13 at 20:54
  • You could use your search skills and find this http://stackoverflow.com/questions/605533/does-casting-to-an-int-after-stdfloor-guarantee-the-right-result OR This may be helpful as well http://www.gnu.org/s/libc/manual/html_node/Rounding-Functions.html – Maksim Vi. Aug 10 '09 at 08:25

2 Answers2

70

The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type.

from the ceil(3) Linux man page.

Sean A.O. Harney
  • 23,901
  • 4
  • 30
  • 30
29

That's because float's range is wider than int's. What would you expect to have if the value returned by these functions did not fit into an int? That would be undefined behaviour and you would be unable to check for that in your program.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 14
    There would not need to be any undefined behaviour - the functions *could* have been specified to return an error value in that case, just like strtol() does if the number to be converted doesn't fit into a long. The reason is simply that the functions would be far less useful if they were restricted to the range of int. – caf Aug 10 '09 at 09:07
  • 1
    @caf: let me disagree. Every time I use floor/ceil, I need to cast the value to int and it is always such that no overflow occurs. This is the rule rather than the exception. –  Oct 09 '21 at 16:51
  • @YvesDaoust: It's not clear exactly what you're disagreeing with? – caf Oct 10 '21 at 23:10
  • @caf: "the functions would be far less useful if they were restricted to the range of int". –  Oct 11 '21 at 08:29