Public Group

#### 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 5235 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 on other sites
this may work, and is prolly fast
#define ROUNDNUM(x) ((int)( x >= .5f ? (x+1.0f) : x ))

##### 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 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 on other sites
Really, it''s like RowanPD said. Add 0.5f to the float and convert it to an int; if the float was x.5 or more, it becomes x+1, if not it becomes x.

##### Share on other sites
Thank you so much!, btw I was replying to moses, but aol takes a bajillion years 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 on other sites
Clueless: Only looks different.. Does the same thing..

[edited by - Mkk on March 23, 2004 9:15:28 AM]

##### 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 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 );

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 30
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631781
• Total Posts
3002316
×