0

I want to display the dollar sign next to its value in the second column, but if I convert the value into a string, the setprecision doesn't work and it displayed more decimals than I would like. Currently the formatting doesn't look good.

My current code:

string unit = "m";
double width = 30.123;
double length = 40.123;
double perimeter = 2 * width + 2 * length;
double area = width * length;
double rate = (area <= 3000) ? 0.03 : 0.02;
double cost = area * rate;
const int COLFMT = 20;

cout << fixed << setprecision(2);
cout << setw(COLFMT) << left << "Length:"
     << setw(COLFMT) << right << length << " " << unit << endl;
cout << setw(COLFMT) << left << "Width:"
     << setw(COLFMT) << right << width << " " << unit << endl;
cout << setw(COLFMT) << left << "Area:"
     << setw(COLFMT) << right << area << " square" << unit << endl;
cout << setw(COLFMT) << left << "Perimeter:"
     << setw(COLFMT) << right << perimeter << " " << unit << endl;
cout << setw(COLFMT) << left << "Rate:"
     << setw(COLFMT) << right << rate << "/sqaure" << unit << endl;
cout << setw(COLFMT) << left << "Cost:"
     << setw(COLFMT) << right << "$" << cost << endl;

Produces this poorly formatted output:

Length:                            40.12 m
Width:                             30.12 m
Area:                            1208.63 square m
Perimeter:                        140.49 m
Rate:                               0.03/square m
Cost:                                  $36.26
acraig5075
  • 10,588
  • 3
  • 31
  • 50
Saim Beg
  • 3
  • 1
  • I would like to state that I have attempted using floor() to round but it displays 36.260000 when converted to string. I tried a few other things but unfortunately cannot seem to figure out how i can display $36.26 with the values 30.123 and 40.123 for width and length respectively. – Saim Beg Oct 25 '19 at 04:27
  • The program shown above already prints "Cost: $36.26", when I ran it. Where's the problem? – Wander3r Oct 25 '19 at 06:00
  • The problem was the bad formatted output, $36.26 didn't line up with other numbers above it. – Saim Beg Oct 25 '19 at 16:43

1 Answers1

1

"Currently the formatting doesn't look good."

That's because std::right pertains to what follows it, in your case "$". So the dollar sign is right-aligned and not the value that follows on afterwards.

What you want is the fully formatted monetary value "$36.26" to be right aligned. So build that up as a string first with stringstream.

stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;
acraig5075
  • 10,588
  • 3
  • 31
  • 50