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

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

本文关键字:显示 符号 何显示 c++ setw setprecision      更新时间:2023-10-16

我想在第二列中的值旁边显示美元符号,但如果我将值转换为字符串,则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:                                  $36.26

"当前格式看起来不太好。">

这是因为std::right与它后面的内容有关,在您的案例中是"$"。因此,美元符号是正确对齐的,而不是随后的价值。

你想要的是完全格式化的货币价值"36.26美元"正确对齐。因此,首先使用stringstream将其构建为字符串。

stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;