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

Started by
8 comments, last by xorjesus 20 years, 1 month ago
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
I study day and night, memorizing the game.
Advertisement
this may work, and is prolly fast
#define ROUNDNUM(x) ((int)( x >= .5f ? (x+1.0f) : x ))
- John Moses
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
R--------------------------------------------------------------------------There is no point in flaming if you've merely poured fuel on your own head
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.
I study day and night, memorizing the game.
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.
-Lord Maz-
Thank you so much!, btw I was replying to moses, but aol takes a bajillion years to post.
I study day and night, memorizing the game.
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]
Writing errors since 10/25/2003 2:25:56 AM
Clueless: Only looks different.. Does the same thing..


[edited by - Mkk on March 23, 2004 9:15:28 AM]
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
[/quote]
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 );
william bubel

This topic is closed to new replies.

Advertisement