Advertisement

Rounding floating point numbers in C++

Started by November 01, 2001 12:15 AM
3 comments, last by Daivam 23 years 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..
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.
Advertisement
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