1. ## floor() and int()

Hi,
I was wondering what's the difference between floor() and int() when taking the nearest smaller integer to a floating number? Which one is prefered?
Thanks and regards!

2. They do different things. floor() rounds down, int() will truncate. The return types differ as well:

floor(-3.5) == -4 (double)
int(-3.5) == -3 (int)

3. >> I was wondering what's the difference between floor() and int() when taking the nearest smaller integer to a floating number?

Conversion from float to int is (potentially) limited, so your best bet would be to stick with floating point specific functions.

EDIT:
>> floor(-3.5) == -4 (double)

Missed that one.

4. Originally Posted by lehe
Hi,
I was wondering what's the difference between floor() and int() when taking the nearest smaller integer to a floating number? Which one is prefered?
Thanks and regards!
It depends whether you needs to put the value of the double into an integer or not. If you don't need to, then you'd just use floor.
Code:
`doubld d2 = floor(d1);`
If you do need to, I would consider using both to be more explicit.
Code:
`int i = int(floor(d));`
By the way, int() as you queried about, is the constructor form of casting. The normal C++ way would be:
Code:
`int i = static_cast<int>(floor(d));`
and the C way is
Code:
`int i = (int)floor(d);`

5. I always thought that if the values are integer and positive the would both return the same value...but that is the only time that is the case...

Code:
```(int) floor (1.1) = 1
(int)1.1 = 1```
If they were negative and integer then ceiling and truncation would give the same

Code:
```(int) ceiling (-1.1) = -1
(int) -1.1 = -1```
could be wrong however...

6. There's also trunc(). :-)

7. Originally Posted by Cactus_Hugger
There's also trunc(). :-)
... is specific to unix (I'm not 100% sure, but suspect it may be specific to particular flavours or versions of unix).

8. Originally Posted by grumpy
... is specific to unix (I'm not 100% sure, but suspect it may be specific to particular flavours or versions of unix).
I don't think so, but I haven't taken to 30+ minutes of booting windows to check. The man page seems to indicate that it should be available in windows:
Code:
```CONFORMING TO
C99, POSIX.1-2001.```

9. I don't think so, but I haven't taken to 30+ minutes of booting windows to check. The man page seems to indicate that it should be available in windows:
CH is correct- trunc is available in C99 standard:

trunc- Truncate to nearest integral value:

double trunc(double x);

returns x rounded to the integer nearest to it but no larger in magnitude

10. Originally Posted by ninety3gd
CH is correct- trunc is available in C99 standard:
This is a C++ forum. C++ is only backward compatible to C89, not forward compatible to C99. trunc() is not included in either the C++ or C89 standards.