#### Archived

This topic is now archived and is closed to further replies.

# Round up/down function

## Recommended Posts

BlueDev    126
Hello, Is there a possible way to find out if my numbers decimal point is greater than or less than .5 and then take the neccessary steps to round up or round down to the nearest number, example:
void main() {
double number = 0.0;

number = 1.6;

// here to find out if .6 is greater than or less than .5, how would I determine that

}

Thanks again. - BlueDev
[edited by - BlueDev on September 1, 2003 2:43:56 PM]
Nacho    205
You´re lucky! I´ve just wrote one a couple of hours ago!!

inline float FixValue(float Value){	double dInteger,dFraction;	dFraction = modf(Value,&dInteger);	if(dFraction<0.0) {		if(dFraction < -0.5)			return  ((float)dInteger-1.0f);		else			return (float)dInteger;	} // End if.	else { // fFraction > 0.		if(dFraction > 0.5)			return ((float)dInteger+1.0f);		else			return (float)dInteger;	} // End else.} // End FixValue().

Hope it helps!

--Ignacio Liverotti
iliverotti@hotmail.com

##### Share on other sites
BlueDev    126
Wow thanks, you just saved me days of trying to figure this out, many thanks Ignacio Liverotti.

- BlueDev

##### Share on other sites
Robot Guy    172
If you have a decent compiler (as I think it's a c99 addition) you could use "round". If not I think that this will also work (it's a bit shorter) :

double round(double val) {  return (val > 0.0) ? floor(val + 0.5) : ceil(val - 0.5);}

This should round correctly (+0.5 -> +1.0 and -0.5 -> -1.0)

[edited by - Robot guy on September 2, 2003 4:43:32 AM]

##### Share on other sites
BitMaster    8651
Floating point values are simply truncated when converting to an int (at least in common languages like Java or C/C++). So (int) (value + 0.5) will behave as you want it to behave.

[edited by - BitMaster on September 2, 2003 4:52:36 AM]