6

I have the folowing example :

double x = 2.5;
int n = (int)x;
int k = (int) floor(x);

Does casting double to int returns the round down number? or I should use floor function?

Anis_Stack
  • 3,306
  • 4
  • 30
  • 53

3 Answers3

16

Be careful with negative numbers. Casting will truncate towards 0. floor will truncate towards negative infinite.

If the value is positive, then both methods return the same truncated value.

user3813674
  • 2,553
  • 2
  • 15
  • 26
  • Right. I totally forgot about negative rounding rules and what rounding up or down means there. – SergeyA Feb 12 '16 at 15:59
7

Well (int) truncates the initial double value (fractional part removed)

  2.1  -> 2
  2.5  -> 2
  2.99 -> 2

it looks like floor, but they're not the same in case of negative numbers:

  (int)-2.1   -> -2
  floor(-2.1) -> -3.0

since floor returns max integer value that less or equal to the given argument

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

Beware of the limitation of int and double.

int main(void)
{
    double val1 = INT_MAX + 10.5;
    int    val2 = val1;

    printf("val1 = %f\nval2 = %d\n", val1, val2);

    return (0);
}

This produce the output below :

val1 = 2147483657.500000
val2 = -2147483648

(I don't know if INT_MAX is standard, sorry).

Tom's
  • 2,448
  • 10
  • 22