Archived

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

C++: What is the fastest way to round a float to a whole num

This topic is 5013 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

I''m looking for a fast way to round a float to a whole number, for example if I have the number 2.797985, I want to round it to 3, if I have the number 3.134 I want to round to it uhh 3

Share this post


Link to post
Share on other sites
I hate to be the first non-ecclesiastic to add to this thread but I''m afraid I''ll have to be.

I don''t think that previous response will work. Did Moses try to put any number above 2 through that #define ?

Just try this:

#define ROUNDNUM(x) ((int)(x + 0.5f))

If my memory serves me right type-casting to int rounds down, so just add half before you do.

Easy.


R

--------------------------------------------------------------------------
There is no point in flaming if you''ve merely poured fuel on your own head

Share this post


Link to post
Share on other sites
That doesn''t work, but thanks for the suggestion. All that that function does is strip the decimal part of from the float number and test if the whole number is bigger than .5, which it will always be unless the float number was 0.

Share this post


Link to post
Share on other sites
Is there anything wrong with

float y = 12.7f;
int x = int( y + 0.5f );

?

Just that it is not a defined type I guess...?

[edited by - Clueless on March 23, 2004 8:36:07 AM]

Share this post


Link to post
Share on other sites
Hello xorjesus,

I have a method that might help.

#include <stdio.h>
#include <math.h>

inline double roundNumber(double value) {
return (value > 0.0) ? floor(value + 0.5) : ceil(value - 0.5);
}

int main() {
float myFloat = 3.75f;

myFloat = (float)roundNumber(myFloat);

printf("%f\n", myFloat);

return 0;
}


This should automatically round up/down depending if the floating point is > 0.5 or < 0.5.


Hope this helps,
[BDS]StackOverflow

Share this post


Link to post
Share on other sites
We round to an integer if the range of the number is between -0.5 and +0.49999~. round(1.5)=2 , round(2.49)=2 . So, if we have the inclusion of -0.5, adding 0.5 to it would yield 0.0. And the exclusion of +0.5 means that if we add 0.5 to that, we exclude +1.0. So, simply adding and casting will round effectively.

xi = (int) ( yf + 0.5 );

Share this post


Link to post
Share on other sites