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 Commented Nov 25, 2010 at 20:49
  • @Darryl Hein - Haha, interesting. Btw, nice docs - those. Commented 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. Commented Nov 25, 2010 at 22:22
  • @gablin - Good point! Commented 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? Commented 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. Commented Nov 26, 2010 at 1:02
  • So.... 100000000000000000000.5 isn't exactly represented, no matter what you do with it? Commented 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. Commented 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. Commented Nov 28, 2010 at 0:30

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.