#### Archived

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

# rounding off a float

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

## Recommended Posts

How do i round of a float? say i have an integer x which is 501 but x must be a power of 2. so: float fPower = log10(x) / log10(2); x = pow(2, fPower); fPower should be rounded off to an integer, how do i do this? Now when fPower is e.g. 8.9 it is used as 8 instead of 9 ---------- Drago

##### Share on other sites
Hey, try tyepcasting the float...if x is an int, fPower will be read into the equation as an intiger...

i know this is simple, and you probalby know better, but here's a little better solution. I dont know of any built in functions, but you could make a simple function to round up for down...like:

int roundNum(float fltNum)
{
int intNum;
float difference;

int intNum = fltNum;

difference = fltNum - (float)intNum;

if(difference >= 0.5)
intNum++;

return intNum;
}

OK, try that...real simple and bare-bones basic rounding function...i did it in a simple test program and it worked without fail (though you might want to change int to a larger variable type if needed)

Email me if it works, or if it doesn't, i'd like to know if i actually helped and i dont come here often...
roosterjm@home.com

Edited by - roosterjm on 4/29/00 10:53:42 PM

##### Share on other sites
Why dun you just think simple ?

int ConvFloat(float a)
{
return( (int)(a+0.5)) ;

}

U see ... if the decimal part is anything less than 0.5, adding 0.5 to a will not add to the interger part of the float. Therefore will be trancated and thus rounded down. If the decimal part is 0.5 or more, the interger part will increase after adding 0.5. After trancation, the float will be rounded up

##### Share on other sites
typecasting int doesn''t round the float, it just truncates the decimal part . To do this, you need your own function. The last guy''s function is pretty good, although i would delare it inline since it would be used so often .

##### Share on other sites
Dont you think thats fast enough? it should be...

========================
Game project(s):
www.fiend.cjb.net

##### Share on other sites
Yup, the "int (a + 0.5)" is a classic trick that works great.

Tim

##### Share on other sites
Just a quick note: the (int)(a+0.5) trick only works for positive numbers. If the number is negative you need (int)(a-0.5).

Edited by - Ranok on 5/4/00 6:54:27 PM

##### Share on other sites
if you wanted pos and neg just have
int (a + 0.5*((a<0)? -1:1))
erm...i think that''s right

##### Share on other sites
hmm .... how abt this

int convStuff( float a)
{
float z = abs(a) ;
int b = int(a/z) ; //so its either -1 or 1, depending on a
return (int(z+0.5)*b) ;
}

##### Share on other sites
haha just do

return (int)(flt + flt<0 ? -0.5 : 0.5);

no fancy stuff needed!

Edited by - adammil on May 9, 2000 2:13:07 PM

• 10
• 13
• 57
• 11
• 84