#### Archived

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

# Rounding numbers in C++

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

## Recommended Posts

Hi buddies! I''m currently needing an algorithm that performs floating point numbers rounding in C/C++, or I would at least like to get the name of the function that is gonna do it for me (getting both the name of the function and the algorithm would be rather nice too). I have already looked for everything named either round, Round, rnd, and so on but I''ve not been able to find anything. Could someone be kind enough to indicate me what I need, please? I thank you all in advance. Prog, Sex & Rock''n''Roll : I don''t like the Prog but the prog likes me.

##### Share on other sites
hmm, maybe i''m getting your question wrong but do you mean just rounding to the nearest integer??

in math.h there are functions called floor and ceil that do this, or you could just convert the float to an int...

##### Share on other sites
floor(num + 0.5) will work fine as long as your numbers are all positive.

How appropriate. You fight like a cow.

##### Share on other sites
if (int(blah + 0.5) != int(blah)) // round up
blah = (int) blah + 1;
else {} // keep it the same

That''s what I think would work best.

##### Share on other sites
quote:
Original post by Xairo
if (int(blah + 0.5) != int(blah)) // round up
blah = (int) blah + 1;
else {} // keep it the same

That''s what I think would work best.

Yikes. Your method requires THREE float-int conversions, which are fairly expensive operations. Even if you were doing it like this, you''d want to do "blah = (int) blah+0.5". Which is pretty much the same as the algorithm I already posted, except less efficient.

How appropriate. You fight like a cow.

##### Share on other sites
Neither of those work for negatives tho !

##### Share on other sites
Hi again, dudes!!

I think floor and ceil are the functions I need. Like you say, I had to get the nearest integer value.
Thank you very much, brothers!!

Prog, Sex & Rock''n''Roll :
I don''t like the Prog but the prog likes me.

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
14
5. 5
frob
12

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633661
• Total Posts
3013226
×