• Advertisement

Archived

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

Round up/down function

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

If you intended to correct an error in the post then please contact us.

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
BlueDev Net [edited by - BlueDev on September 1, 2003 2:43:56 PM]
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

Share this post


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

- BlueDev

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

  • Advertisement