C++货币输出

标签 c++ floating-point iostream currency

我现在正在学习 C++ 类(class),并且已经完成了我的期末作业。然而有一件事困扰着我:

虽然我有针对特定输出的测试的正确输出,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);

示例 here .

这种方法有什么优势?

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

关于C++货币输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15327706/

相关文章:

c++ - 从内置类型到自定义类的转换

c++ - 在 C++ 中创建自定义类的多个实例

floating-point - 浮点相加与浮点乘以整数的精度

c++ - 如何枚举最小值和最大值之间的所有浮点值

C++ getline传文件或cin

c# - 通过 DllImport 调用非托管函数时堆损坏

c++ - 在 OSX Lion 上使用 g++ 的 SDL

floating-point - 为什么不使用 Double 或 Float 来表示货币?

c++ - 循环丢弃来自标准输入、Linux C++ 的虚假变量输入

json - Jasper Report - 将 json IO 流传递给子报表