PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

[FIXED] How do I move a decimal point left while maintaining number of digits displayed?

 August 12, 2022     c++, decimal, floating-point, setw     No comments   

Issue

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.


Solution

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



Answered By - Ruks
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing