# (C++) How would you go about rounding numbers?

• 10-14-2002
jeffcoulter
(C++) How would you go about rounding numbers?
Ok Basically when I am run the program it will add both numbers 1.67 + 1.32 and give the result 3.00. Clearly, the sum of the displayed numbers should be 2.99 and not 3.00. The problem is that although the values in a and b have been displayed with two decimal digits, they were added internal to the program as three-digit numbers. The solution is to round the values in a and b before they are added to the statement c = a + b;

Using the int cast, how would I be able to round the values in variables a and b to the nearest hundredth(penny value) before they are added?

Code:

```#include <iostream.h> #include <iomanip.h> void main(void) {   float a, b, c; a = 1.674; b = 1.322; cout << setprecision(3) << a << endl; cout << setprecision(3) << b << endl; cout << "----\n"; c = a + b; cout << setiosflags(ios::showpoint)     << setprecision(3) << c << endl; }```
• 10-14-2002
bonkey
Here is one way to round using a class and overiding the = operator.

Code:

```class Math { public:         int x;         operator int()         {                 return x;         }         int operator=(const double &num)         {                 double y;                 if ( num < 0 )                         y=num-.5;                 else                         y=num+.5;                 x=int(y);                 return x;         } };```
• 10-14-2002
Sang-drax
Re: (C++) How would you go about rounding numbers?
Quote:

Originally posted by jeffcoulter
The problem is that although the values in a and b have been displayed with two decimal digits, they were added internal to the program as three-digit numbers.

Forget that.

There's nothing strange with you program above. 3.00 is the correctly rounded value to 2.998
• 10-17-2002
cid666
you mean 2.996
• 10-17-2002
Sang-drax
Yes
• 09-19-2005
spanglej
This may help
double a, b, c;
int temp_round;

a = 1.674;
b = 1.322;

cout.setf(ios::fixed);
cout << setprecision(2) <<"a="<<a<< endl;
cout <<"b="<<b<< endl;
cout << "----\n";

/*
The following statement multiplies the double identifier named "a" (value of 1.67by 100 resulting in 167.4 and stores the result in an integer variable named temp_round. Due to truncation (float to int) temp_round holds the value of 167 (the .4 is truncated)
*/

temp_round= int(a*100);

/*
The following statement converts the variable temp_round (value of 167) to a double (value of 167.00) and divides it by 100.0 (resulting in 1.67) and stores it back the double identifier named "a"
*/
a = double(temp_round)/100.0;

//used the same conversion
temp_round= int(b*100);
b = double(temp_round)/100.0;

c = a + b;

cout << setprecision(2)<< "c = " <<c<< endl;
system ("pause");