![](smile.gif)
🎉 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++
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..
![](smile.gif)
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 ...
~~~~~~~~~~
FreeBSD.org - worship the Daemon!
float myFloat = 8.6487f;printf("%.2f", myFloat);
~~~~~~~~~~
FreeBSD.org - worship the Daemon!
Or, if you needed to have that rounded value put in another variable:
You could also use fmod, but I prefer integer truncation.
[Resist Windows XP''s Invasive Production Activation Technology!]
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.
AOL, so easy to use, no wonder it''s nothing but a bunch of retards
Spyder''s Web Games
#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
![](http://www.geocities.com/webspynner_99/spider.gif)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement