Search code examples
c++stringsetw

How can I display a $ sign with a value while using setw and setprecision in c++


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

Solution

  • "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;