Adding the Decimal Place with setpercision

Hi Guys!

I was finishing up my project, and I am trying to get the decimal point to show as a dollar amount, so two decimals. I used setpercision(2) because I thought that would only affect the amount of digits after the decimal place. However, it is affecting the whole number.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <iomanip>
using namespace std;

double CalculateAmountPerPerson(double TotalBill, double TipPercentage, int NumFriends) //Identifying the functions and what they respresent 
{
	double totalTipPerPerson = (TotalBill * TipPercentage) / NumFriends; 
	double totalPerPerson = (TotalBill / NumFriends) + totalTipPerPerson;
	return totalPerPerson;
}

double CalculateAmountPerPerson(double TotalBill, double TipPercentage, int NumFriends); /* I am using doubles because I
																						 want to be able to show the full amount w/ cents*/
int main()
{
	int friends;
	double damage;
	double tip;

	cout << "So whats the damage...how much do you owe?" << endl;
	cin >> damage;
	
	while (damage < 1)
	{
		cout << " So why do you need me if your meal was free...? Try again" << endl;
		cin >> damage;
	}
	cout << "Ok thats not too bad... well how many friends will pitch in?" << endl;
	cin >> friends;
	while (friends < 1)
	{
		cout << " You have no friends.. that so sad... but again why do you need me?" << endl;
		cout << "Try again.." << endl;
		cin >> friends;
	}
	
	for (tip = .10; tip <= .30; tip += .025)
	{
		cout << "If you are kind enough to leave a " << tip * 100 << "%, each friend pays $";
		cout << setprecision(2) << CalculateAmountPerPerson(damage, tip, friends) << ".";
		cout << endl;
	}

	system("PAUSE");
		return 0;
	
			
}
If you're using std::setprecision you probably also want to use std::fixed.

 
cout << fixed << setprecision(2) << CalculateAmountPerPerson(damage, tip, friends) << ".";
That worked! Thank you so much! Could you please "remind" me what the fixed does?
By default it will count the precision from the most significant digit.

1
2
// This will output the two most significant digits 1 and 2.
cout << setprecision(2) << 123.456;


If you use fixed it will start counting the precision from the decimal mark.

1
2
// This will output the whole integer part and two digits of the fractional part.
cout << fixed << setprecision(2) << 123.456;
Hello LannaBanna,

In addition to Peter87's answer the other alternative to fixed is scientific notation. You can read about it here:
http://www.cplusplus.com/reference/ios/fixed/?kw=fixed

Hope that helps,

Andy
Topic archived. No new replies allowed.