Round up/down function

Started by
4 comments, last by BlueDev 20 years, 7 months ago
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 BlueDev Net [edited by - BlueDev on September 1, 2003 2:43:56 PM]
[/quote]
Advertisement
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
Wow thanks, you just saved me days of trying to figure this out, many thanks Ignacio Liverotti.

- BlueDev
[/quote]
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]
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]
There are some C standard library functions which do this
-------------"On two occasions, I have been asked [by members of Parliament], 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?' I am not able to rightly apprehend the kind of confusion of ideas that could provoke such a question."- Charles Babbage (1791-1871)

This topic is closed to new replies.

Advertisement