I currently have a function that takes in a vector of structs, including all floats, and should return some values after a simple calculation.
My cout function is simply
void taxPrint(std::vector<TaxPayer> &citizen)
{
int loops = 0;
std::cout << "\nTaxes due for this year: \n" << std::endl;
do
{
std::cout << "Tax Payer #" << loops << " : $" << citizen[loops].taxes << std::endl;
loops++;
}
while (loops + 1 <= SIZE);
and the resulting output in console is
Tax Payer #0 : $450000
Tax Payer #1 : $210000
That said, I want it to be
Tax Payer #0 : $4500.00
Tax Payer #1 : $2100.00
I've been messing around with setw() and setprecision() but I don't exactly understand how they work.
std::setw
, actually has nothing to do with value precision, it is for padding string with prefixes like: 001-0123-9124
(Padded with 0
)
Example: std::cout << std::setfill('0') << std::setw(5) << 5 << std::endl;
will print 00005
Here is how to use it using std::fixed
and std::setprecision
:
void taxPrint(std::vector<TaxPayer> &citizen)
{
int loops = 0;
std::cout << "\nTaxes due for this year: \n" << std::endl;
do
{
std::cout << "Tax Payer #" << loops << " : $" << std::setprecision(2)
<< std::fixed << citizen[loops].taxes / 100. << std::endl;
loops++;
}
while (loops + 1 <= SIZE);
} // Don't miss this bracket!
Also, look at this question to know more about specifying a fixed precision to a value...