Jac*_*ack 2 c++ floating-point iostream currency
我现在正在参加C++课程并完成了我的最终任务.然而,有一件事让我烦恼:
虽然我对测试正确的输出上的特定输出时,basepay
应该是133.20
,它会显示为133.2
.有没有办法让这个显示额外的0而不是让它关闭?
任何人都知道它是否可能以及如何做到这一点?先感谢您
我的代码如下:
cout<< "Base Pay .................. = " << basepay << endl;
cout<< "Hours in Overtime ......... = " << overtime_hours << endl;
cout<< "Overtime Pay Amount........ = " << overtime_extra << endl;
cout<< "Total Pay ................. = " << iIndividualSalary << endl;
cout<< endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%% EMPLOYEE SUMMARY DATA%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" <<endl;
cout<< "%%%% Total Employee Salaries ..... = " << iTotal_salaries <<endl;
cout<< "%%%% Total Employee Hours ........ = " << iTotal_hours <<endl;
cout<< "%%%% Total Overtime Hours......... = " << iTotal_OvertimeHours <<endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl;
cout<< "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" << endl;
Run Code Online (Sandbox Code Playgroud)
如果您想以C++方式进行,并且可以使用C++ 11标志进行编译,则可以使用标准库:
// Note: the value in cents!
const int basepay = 10000;
// Create a stream and imbue it with the local configuration.
std::stringstream ss;
ss.imbue(std::locale(""));
// The stream contains $100.00 (assuming a en_US locale config)
ss << std::showbase << std::put_money(basepay);
Run Code Online (Sandbox Code Playgroud)
这里的例子.
这种方法有哪些优点?
使用cout.precision设置精度,并使用fixed切换定点模式:
cout.precision(2);
cout<< "Base Pay .................. = " << fixed << basepay << endl;
Run Code Online (Sandbox Code Playgroud)
小智 5
是的,这可以使用流操纵器.例如,将输出设置为固定浮点表示法,定义精度(在您的情况下为2)并将填充字符定义为"0":
#include <iostream>
#include <iomanip>
int main()
{
double px = 133.20;
std::cout << "Price: "
<< std::fixed << std::setprecision(2) << std::setfill('0')
<< px << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果你喜欢C风格的格式,这里有一个使用printf()
实现相同的例子:
#include <cstdio>
int main()
{
double px = 133.20;
std::printf("Price: %.02f\n", px);
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.祝好运!