🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Rounding floating point numbers in C++

Started by
3 comments, last by Daivam 22 years, 8 months ago
Say you have a float variable that''s holding a value of 8.6487 and you would like to print that value rounded to the second decimal place(I.e. 8.65), how would you do that? Thanks..
Advertisement
You can set the precision to which to print to using ostream objects in C++, or format strings in C. I forget exactly how, but that''s why we have search engines and MSDN.
Hmm. I can''t remember if this method rounds or not ...
  float myFloat = 8.6487f;printf("%.2f", myFloat);  


~~~~~~~~~~
FreeBSD.org - worship the Daemon!
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
Or, if you needed to have that rounded value put in another variable:
  float Original = 8.6487f;float RoundedToTwo = ((int)(Original * 100.0f))/100.0f  

You could also use fmod, but I prefer integer truncation.

[Resist Windows XP''s Invasive Production Activation Technology!]
I''ve always like the flexible rounder, one that let''s you pick the precision.

  #include <math.h>float round(float num,int place){   int power=pow(10,place);   return ((float)((int)(power*num))/(float)power);}  


AOL, so easy to use, no wonder it''s nothing but a bunch of retards

Spyder''s Web Games

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

This topic is closed to new replies.

Advertisement