2

My question is; is there a functional difference between rounding a double down to an int via roundedInt = (int)unRoundedDouble and roundedInt = (int)(floor(unRoundedDouble)) ?

I've seen the latter used in code, and thought that maybe it's for safety or functional reasons, but can't figure out what would be handled differently.

Also: the rounded Double will not be too large to fit into an int, that's determined beforehand.

BigBadWolf
  • 603
  • 2
  • 8
  • 17

2 Answers2

3

They are fundamentally different. Cast to int will truncate the non-integer part toward 0. floor will do the same, but toward, -infinity.

Example:

double d = -1.234;
printf("%d %d\n", (int)d, (int)floor(d));

Yields:

-1 -2
dmg
  • 7,438
  • 2
  • 24
  • 33
2

The solution with floor works well for negative numbers, the casting version is incorrect mathematically -- if by rounding down you mean the floor operation.

So #floor always work as the mathematical floor operation, the casting behaves the same for positives. However the casting on negatives behaves like the ceiling operation.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • Could you explain how it is incorrect, or give a case where it wouldn't work? Thanks! :) (nevermind, I just realized that it would round up negatives.) – BigBadWolf Jan 22 '15 at 10:16
  • 1
    @BigBadWolf casting truncates the decimal part while `floor` calculates the real mathematical floor – phuclv Jan 22 '15 at 10:28