Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Round function ? 3

Status
Not open for further replies.

rwong

Programmer
Apr 16, 2002
68
CR
Is there any function in Visual C++ to round a floating point number? I revised the math.h library and did not find any
 
The way I round numbers is by adding 0.5 and casting it to an integer. That rounds to the nearest whole number. To round to a different decimal precision, first multiply the number by 10^n, round that to the nearest whole number, then divide by 10^n.
 
Hi

Say you wanr nNbr decimals out of the number fNbr, here is another way:

CString str;

str.Format( "%.*f", nNbr, fNbr);

Now you cast str to what you need if required

HTH

Thierry
 
dds82,
Thats a good idea. There is the floor() function of <cmath> but I tried it and didn't seem to work right!? Anyhow, adding .5 is a good idea!

CES
 
#include <cmath>
#include <iostream>

using namespace std;

void main(){
float num = 0;
while (true){//CTRL + C to quit
cin>>num;
cout<<&quot;num rounded down to nearest integer &quot;<<floor(num)<<endl;
cout<<&quot;num rounded up to nearest integer &quot;<<ceil(num)<<endl;
cout<<&quot;num rounded nearest to nearest integer &quot;<<floor(num + 0.5)<<endl;
}

}
 
Well, besides bad grammer, this will do your rounding. :p
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top