6

I think every single time I've used Math.Ceiling or its language variant, I've always had to cast it to an integer. I mean... that's the whole point, isn't it? To get a whole number. So why doesn't it just return an int?

2 Answers 2

11

For one, REALs/FLOATs usually have a much greater range. The result might not fit into an INTEGER.

4
  • This is exactly what the PHP documentation says for it's function: php.net/ceil Nov 25, 2010 at 20:49
  • @Darryl Hein - Haha, interesting. Btw, nice docs - those.
    – Rook
    Nov 25, 2010 at 20:57
  • 4
    One should also note that just as decimals sometimes can't be represented exactly with float, the same goes for really large integers.
    – gablin
    Nov 25, 2010 at 22:22
  • @gablin - Good point!
    – Rook
    Nov 25, 2010 at 22:27
2

Smalltalk's does.

100000000000000000000.5 ceiling => 100000000000000000000

100000000000000000000 is a LargePositiveInteger, meaning an integer that uses more than 32 bits in its representation.

As Michael points out, the above answer is wrong. I didn't notice that while the answer was an integer the answer was wrong because the float loses precision. So instead here's another, CORRECT, version, which works because we don't use floats:

(100000000000000000000 + (1 / 2)) ceiling => 100000000000000000001
6
  • Wait... why wasn't that rounded up then?
    – mpen
    Nov 26, 2010 at 0:16
  • @Ralph: Because the number has more digits than a floating point number can represent, so you lose some precision. Nov 26, 2010 at 1:02
  • So.... 100000000000000000000.5 isn't exactly represented, no matter what you do with it?
    – mpen
    Nov 26, 2010 at 1:22
  • @Ralph: Yes. 64-bit floating point can only represent all integers exactly up to 2^53, which gives about 16 digits of precision. If you need more than that, you will have to use a decimal type or an arbitrary precision library. Some C and C++ compilers/architectures also support 80-bit "long doubles" with around 19 digits. Nov 27, 2010 at 21:33
  • Well, my point was that your answer is misleading. Even with the amendment... 1/2 == 0, doesn't it (at least in C++ it is)? You don't have any floats in there, so ceiling isn't really doing anything at all.
    – mpen
    Nov 28, 2010 at 0:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.