Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ currency output

I am taking a C++ course right now and have completed my final assignment. However there is one thing that is bugging me:

Though I have the correct outputs for the testing on a particular output, the basepay should be 133.20 and it is displaying as 133.2. Is there a way to have this display the extra 0 rather than leaving it off?

Anyone know if it's possible and how to do it? Thank you in advance

My code is below:

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;
like image 236
Jack Avatar asked Nov 28 '22 08:11

Jack


2 Answers

If you want to do it in a C++ way, and you can compile with C++11 flags, you can use the standard library:

// 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);

Example here.

What advantages have this approach?

  • It uses the local configuration, so the output will be coherent in any machine, even for the decimal separator, thousand separator, money symbol and decimal precission (if needed).
  • All the format effort is already done by the std library, less work to do!
like image 170
PaperBirdMaster Avatar answered Dec 10 '22 12:12

PaperBirdMaster


use cout.precision to set precision, and fixed to toggle fixed-point mode:

cout.precision(2);
cout<< "Base Pay .................. = " << fixed << basepay << endl;
like image 33
Mike Dinescu Avatar answered Dec 10 '22 11:12

Mike Dinescu