floats to integers

Write here if you have problems with your C source code

Moderator: Board moderators

Post Reply
User avatar
Pier
New poster
Posts: 38
Joined: Thu Mar 27, 2003 9:12 pm
Location: Aguascalientes, Mexico
Contact:

floats to integers

Post by Pier » Sun Jun 11, 2006 6:40 pm

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) );
}
There are 10 kind of people on this world: those who understand binary and those who don't!

User avatar
Martin Macko
A great helper
Posts: 481
Joined: Sun Jun 19, 2005 1:18 am
Location: European Union (Slovak Republic)

Re: floats to integers

Post by Martin Macko » Sun Jun 11, 2006 7:55 pm

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.

mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Post by mf » Sun Jun 11, 2006 8:20 pm

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.

User avatar
Pier
New poster
Posts: 38
Joined: Thu Mar 27, 2003 9:12 pm
Location: Aguascalientes, Mexico
Contact:

Post by Pier » Sun Jun 11, 2006 9:14 pm

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))
There are 10 kind of people on this world: those who understand binary and those who don't!

Post Reply

Return to “C”