Page 1 of 1

floats to integers

Posted: Sun Jun 11, 2006 6:40 pm
by Pier
Hi!

It seems that the easiest way to change from floats to ints is by casting, but this may lead to errors. In Pascal I use round, but C lacks of a similar function. I'm currently using this function but I want to know if there's a better way.

Code: Select all

long float_to_int(double fX) {
   return((fX -((long) fX) < 0.5) ? ((long) fX) : ((long) fX+1) );
}

Re: floats to integers

Posted: Sun Jun 11, 2006 7:55 pm
by Martin Macko
Pier wrote:It seems that the easiest way to change from floats to ints is by casting, but this may lead to errors. In Pascal I use round, but C lacks of a similar function. I'm currently using this function but I want to know if there's a better way.
You have several possibilities:

double floor(double x): rounds x down to the nearest integer.
double ceil(double x): rounds x up to the nearest integer.
double round(double x): rounds x to the nearest integer, but round halfway cases away from zero.
double trunc(double x): round x to the nearest integer not larger in absolute value.

Do not forget to #include <math.h> and compile with the -lm flag.

Posted: Sun Jun 11, 2006 8:20 pm
by mf
UVa's compiler doesn't have round() and trunc().

You can use (int)(x+0.5*(x<0?-1:1)) for rounding to nearest integer.

Posted: Sun Jun 11, 2006 9:14 pm
by Pier
Hi!
double floor(double x): rounds x down to the nearest integer.
double ceil(double x): rounds x up to the nearest integer.
double round(double x): rounds x to the nearest integer, but round halfway cases away from zero.
double trunc(double x): round x to the nearest integer not larger in absolute value.
I knew about floor and ceil, but not about round and trunc. Are they also included in math.h? Are they ANSI C?
You can use (int)(x+0.5*(x<0?-1:1)) for rounding to nearest integer.
Seems nice, but should it be better to avoid the multiplication? (int)(x+(x<0?-0.5:0.5))