4

I have a number (let's say, 34), and I want to find its next multiple of ten. I can do this by:

  1. Dividing the number by 10
  2. Rounding it up to a whole number
  3. Multiplying by 10.

After a bit of research, I discovered that this is the code for that in Objective C:

int number = 34;
int roundedNumber = ceil((double)number/10)*10;

My question is: what is the (double) for, and why does removing (double) cause it to round down instead of up?

I understand from googling that changes the float format to "double precision" but, to be honest, this is way too complicated for me. Can anyone provide a simple explanation of what it is doing?

mskfisher
  • 3,028
  • 3
  • 31
  • 47
Ric Levy
  • 956
  • 1
  • 15
  • 33

2 Answers2

5

If you don't have the cast the following happens (if number is 34).

  1. Using integer arithmetic, number/10 is number/10 rounded down, ie 3.
  2. ceil(3) = 3
  3. 3*10 = 30

If you have the cast, the following happens:

  1. (double)number = 34.0
  2. 34.0 / 10 = 3.4
  3. ceil(3.4) = 4.0
  4. 4.0*10 = 40

The important thing to realise is Integer division always rounds towards 0.

Nick Fortescue
  • 40,193
  • 23
  • 99
  • 131
  • Ahhhh I get it! I thought that it was always float, but adding `double` made it some sort of new-fangled even-better "double precision float". I didn't realise that it defaulted to int. I'm marking your question as the answer because it is a more step-by-step beginner-friendly explanation than Ignacio's. – Ric Levy May 12 '11 at 11:05
  • 3
    @Ric: It doesn't "default" `int`, you *declared* it `int`. – Ignacio Vazquez-Abrams May 12 '11 at 11:40
  • So if I had declared it `float`, would I not have needed the `double`? – Ric Levy May 12 '11 at 11:42
  • @Ric: if you'd declared it float or double you wouldn't have to cast. When faced with floating point number divided by an integer (the '10' constant), the integer is automatically converted to the same floating point type before the operation occurs — see 6.3.1.8 in the C99 spec. – Tommy May 12 '11 at 12:33
4

It casts number as a double so that float division is performed instead of integer division. Compare 1/2 versus 1.0/2.

Ignacio Vazquez-Abrams
  • 699,552
  • 132
  • 1,235
  • 1,283