Jump to content
  • Advertisement

Archived

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

KurtCPP

Rounding numbers in C++

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

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!