Public Group

#### Archived

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

# Round up/down function

This topic is 5403 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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]
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
Wow thanks, you just saved me days of trying to figure this out, many thanks Ignacio Liverotti.

- BlueDev

##### Share on other sites
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
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]

##### Share on other sites
There are some C standard library functions which do this

• 32
• 12
• 10
• 9
• 9
• ### Forum Statistics

• Total Topics
631349
• Total Posts
2999473
×