Using setprecision

What is the proper placement of setprecision(2) so that I can set the decimals to always be at 2 points when displaying pennies and dollars. I am using it in a double pennies program.

This first snippet is from the table that creates each days salary that doubles with each day.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  double doublePennies(int days, double pennies)
{
	double penniesToDollarsDivisor = 0.01;
	int counter;
	double numberOfPennies = 1;
	numberOfPennies = numberOfPennies * penniesToDollarsDivisor;
	
	cout << "Day\tPay" << endl;
	cout << "------------------" << endl;
	for (counter = 1; counter <= days; counter++)
	{
		cout << counter << "\t$" << numberOfPennies << endl;
		pennies = pennies + numberOfPennies;
		numberOfPennies = numberOfPennies * 2;
	}

	return pennies;
}


This second snippet is when the total is displayed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void showSalary(int days, double pennies)
{
	cout << "------------------" << endl;

	//If statement to determine singular form of day for 1 day or plural form for more than 1 days
	if (days == 1)
	{
		cout << "Total Pay: $" << pennies << " for " << days << " day." << endl << endl;
	}
	else
	{
		cout << "Total Pay: $" << pennies << " for " << days << " days." << endl << endl;
	}
}


And finally. Here is an overview of my complete program. Feel free to offer pointers or critique. It is for an Introduction to programming class. We create the programs in Flowgorithm then transfer them to pseudocode and C++ with some tweaking.

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iomanip>


using namespace std;

// Headers
string toString(double);
int toInt(string);
double toDouble(string);
int getDays();
double doublePennies(int days, double pennies);
void showSalary(int days, double pennies);

int main()
{
	// Declare variables
	int days;
	double pennies = 0;                               //Accumulator for total pennies
	string keepGoing = "yes";                         //Used to exit loop and end program

	while (keepGoing != "-1")                                                      //While Loop with sentinel value of -1
	{
		days = getDays();
		pennies = doublePennies(days, pennies);
		showSalary(days, pennies);
		cout << "(Enter yes to run the program again. Or enter -1 to exit the program.) ";
		cin >> keepGoing;
		cout << endl;
		pennies = 0;                                                                // Resets pennies accumulator back to 0.
	}
	return 0;
}

int getDays()
{
	// Declare local variables
	int days;

	// Ask the user the amount of days work and receive input
	cout << "How many days did you work? ";
	cin >> days; 
	cout << endl;

	return days;                                                                   //Returns the value of days to main
}

double doublePennies(int days, double pennies)
{
	double penniesToDollarsDivisor = 0.01;
	int counter;
	double numberOfPennies = 1;
	numberOfPennies = numberOfPennies * penniesToDollarsDivisor;
	
	cout << "Day\tPay" << endl;
	cout << "------------------" << endl;
	for (counter = 1; counter <= days; counter++)
	{
		cout << counter << "\t$" << numberOfPennies << endl;
		pennies = pennies + numberOfPennies;
		numberOfPennies = numberOfPennies * 2;
	}

	return pennies;
}
//Function to display total salary
void showSalary(int days, double pennies)
{
	cout << "------------------" << endl;

	//If statement to determine singular form of day for 1 day or plural form for more than 1 days
	if (days == 1)
	{
		cout << "Total Pay: $" << pennies << " for " << days << " day." << endl << endl;
	}
	else
	{
		cout << "Total Pay: $" << pennies << " for " << days << " days." << endl << endl;
	}
}

//The following implements type conversion functions.
string toString(double value) { //int also
	stringstream temp;
	temp << value;
	return temp.str();
}

int toInt(string text) {
	return atoi(text.c_str());
}

double toDouble(string text) {
	return atof(text.c_str());
}

There are some examples of how to use setprecision() here:
http://www.cplusplus.com/reference/iomanip/setprecision/

Also, you may sometimes wish to use setprecision and then set the stream back to its default afterwards. An example of that can be found here:
https://stackoverflow.com/questions/12560291/set-back-default-precision-c

And, of course, you also need to include the <iomanip> header, as you already have done.
Last edited on
closed account (E0p9LyTq)
Unfortunately std::cout and std::setprecision() do NOT give you the level of control that C's printf() has. You can only set the total number of digits that get displayed, whole number and decimal digits.

Your idea of working with whole number pennies integers is a good one. When you want to output an amount in standard US dollar amounts ($xxx.yy) you can simply cast the amount to a floating point number and divide by 100.0. static_cast<double> (amount) / 100.0 for example.

12345 becomes 123.45 or 1234 becomes 12.34
I am still using sprintf for doubles when I need fine control. You can fight the poor c++ interface, or you can borrow a line or 2 of C. I prefer the C, but to each their own.
Thanks guys I will mess around with that info. I ended up finding some info in youtube that helped. I only know the very basics of C++. In my programming class we aren't really focusing on learning code we are more focused on the design of programs. So alot of that looks foreign to me. I like it this way though because it keeps me from just adding anything random in my code and accidentally making it work without knowing the "why" of how it works.

1
2
3
4
                cout << counter << "\t$";
		cout << fixed << showpoint << setprecision(2) << numberOfPennies << endl;
		pennies = pennies + numberOfPennies;
		numberOfPennies = numberOfPennies * 2;


1
2
3
4
5
6
7
8
9
{
		cout << fixed << showpoint << setprecision(2) << "Total Pay: $" << pennies << " for ";
		cout << days << " day." << endl << endl;
	}
	else
	{
		cout << fixed << showpoint << setprecision(2) << "Total Pay: $" << pennies << " for ";
		cout << days << " days." << endl << endl;
	}


This code seems to work so far with every input I give it up to 20. Before this code it would round some numbers up. For example the total pennies earned for 20 days would round up to 10485.8 from the actual amount of 10485.75

floating point types cannot represent some values exactly. So on top of getting it to print as you like, there are limitations to the underlying type as well. Many programs that handle money just make the smallest unit = 1, and use integers; for $USA that means a penny is 1 so all your dollars are stored as $*100 etc. If you need fractions of cents, you would have some rules on how that should be handled and how precise you need to be.
Last edited on
Hello ChimpCoder,

Over time I have found that cout << fixed << showpoint << setprecision(2); works the best. This bit of code only needs to be done once before it is needed and it will affect every "cout" statement after that until any part of it is changed or the program ends.

Hope that helps,

Andy
Topic archived. No new replies allowed.