在 C++ 中使用 setw 和 setprecision 时如何显示带有值的 $ 符号

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

我想在第二列的值旁边显示美元符号,但如果我将该值转换为字符串,setprecision 不起作用,它显示的小数位数比我想要的多。目前格式看起来不太好。

我当前的代码:

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;

生成格式不正确的输出:

Length:                            40.12 m
Width:                             30.12 m
Area:                            1208.63 square m
Perimeter:                        140.49 m
Rate:                               0.03/square m
Cost:                                  .26

"Currently the formatting doesn't look good."

那是因为 std::right 与它后面的内容有关,在您的例子中是“$”。所以美元符号是右对齐的,而不是之后的值。

您想要的是完全格式化的货币值“$36.26”右对齐。因此,首先使用 stringstream.

将其构建为字符串
stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;