c++货币输出

C++ currency output

本文关键字:输出 货币 c++      更新时间:2023-10-16

我正在上一门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;

如果你想用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);

例子。

这种方法有什么优点?

  • 使用本地配置,因此输出在任何机器上都是一致的,即使是小数分隔符,千位分隔符,货币符号和十进制精度(如果需要)。
  • 所有的格式化工作都已经由std库完成,更少的工作要做!

使用cout。Precision为设定精度,fixed为切换定点模式:

cout.precision(2);
cout<< "Base Pay .................. = " << fixed << basepay << endl;

是的,这可以使用流操纵符来实现。例如,将输出设置为固定的浮点表示法,定义精度(在您的示例中为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;
}

如果您更喜欢c风格的格式,这里有一个使用printf()实现相同格式的示例:

#include <cstdio>
int main()
{
    double px = 133.20;
    std::printf("Price: %.02fn", px);
}

希望有帮助。好运!

看看这个:

int main()
{
    double a = 133.2;
    cout << fixed << setprecision(2) << a << endl;
}

输出

133.20

您可以更改cout属性:

cout.setf(ios::fixed);
cout.precision(2);`

现在cout << 133.2;将打印133.20

你需要看一下精度和固定

#include <iostream>
int main()
{
    double f = 133.20;
    // default
    std::cout << f << std::endl;
    // precision and fixed-point specified
    std::cout.precision(2);
    std::cout << std::fixed << f << std::endl;
    return 0;
}