Need Help with C++ regarding decimals

codes are below and need help with the last step, the total cost should be 600 * 21.77 * 0.02 + 600 * 21.77, which is 13278.24, but it shows only 13278.2, please explain...thx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  
#include <iostream>
using namespace std;
int main()
{
 double quantity;
 double cost;
 double rate;
 double stockcost;
 double commission;
 double totalcost;

 cout<<"Program to compute the total cost of stock brokerage."<<endl;

 quantity = 600;
 cost = 21.77;
 rate = 0.02;
 stockcost = quantity * cost;
 commission = quantity * cost * rate;
 totalcost = stockcost + commission;

 cout<<"Stock Price = "<<cost<<endl;
 cout<<"Amount Bought = "<<quantity<<endl;
 cout<<"Commision Rate = "<<rate<<endl;
 cout<<"Stock Purchase Cost = "<<stockcost<<endl;
 cout<<"Stock Commission = "<<commission<<endl;
 cout<<"Total Cost = "<<totalcost<<endl;

 system("pause");
 return 0;
}
 
Put at the beginning these lines:

1
2
        cout << fixed;
	cout.precision(2);


if you want 2 decimal positions.
The default std::cout formatting seems to be the gremlin.

Tell it that precision is 2 and notation is "fixed". See
http://www.cplusplus.com/reference/ios/fixed/
http://www.cplusplus.com/reference/ios/ios_base/precision/
I wonder how come the commission is showing to the hundredth but not the total ? I am a newbie, could someone explain?
When outputting floating point numbers, cout has a default precision of 6 — that is, it assumes all variables are only significant to 6 digits, and hence it will truncate anything after that.

For more info please take a look here:

http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/

Last edited on
if i put

1
2
cout << fixed;
cout.precision(2);


It will show all number to the hundredth, is it possible to make the integers to show like 1 instead of 1.00 when its a whole number ? and when it has decimals, show it to the hundredth ?
Yes, it is possible! See an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>  
#include <iomanip>

using namespace std;

int main () 
{
  double x = 12.345;
  double y = 6789.12;
  int a = 14;
  int b = 31;
  cout << "a = " << a << '\n';
  cout << fixed << setprecision(5) << "x = " << x << '\n';
  cout << "b = " << b << '\n';
  cout << fixed << setprecision(8) << "y = " << y << '\n';
  return 0;
}

Here's the output:

1
2
3
4
a = 14
x = 12.34500
b = 31
y = 6789.12000000

Happy programming! ;)

Here's the output:

a = 14
x = 12.34500
b = 31
y = 6789.12000000




thx, but the number would show some zeroes, how can i make it default that it wont show any zeroes but have more digits to show ?
Please take a look at the links given by keskiverto in his erlier post.
you sad double quantity and give him int number.
@Rakanoth

Who are you to judge people? So man, if you haven't any help here, please, move on...
Topic archived. No new replies allowed.