Search code examples
cfloating-point-conversionmath.h

C: Better method for rounding down double to int


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.


Solution

  • 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