1

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.

Cartino
  • 41
  • 1
  • 7
  • 1
    What is `citizen[loops].taxes`? Please try to create a [mcve] to show us. – Some programmer dude Feb 02 '19 at 03:06
  • I can remove that from the example altogether, my issue is strictly with how to display the correct decimals – Cartino Feb 02 '19 at 03:07
  • No you shouldn't really remove it, since it seems to be a key part of your problem. With the output you show it seems to be an *integer* value, which means there are no decimals to display. – Some programmer dude Feb 02 '19 at 03:08
  • It's a float. I'm just talking about a function that outputs these numbers like I said, but if you want to see more the full program I have it here: https://stackoverflow.com/questions/54488995/c-vectors-of-structs-and-passing-them-error-process-returned-1073741819 – Cartino Feb 02 '19 at 03:11
  • For starters, have you tried to divide the value by `100`? – Some programmer dude Feb 02 '19 at 03:16
  • I guess I didn't think of that. Out of curiosity though, is there a way to handle this with just tools provided by iomanip? – Cartino Feb 02 '19 at 03:20
  • No, since your value isn't what you want, you can't "magically" insert decimal points where it doesn't belong. You need to print the correct value. – Some programmer dude Feb 02 '19 at 03:23

1 Answers1

0

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...

Ruks
  • 3,886
  • 1
  • 10
  • 22