How to align numbers after decimal in C++ output

时间:2016-07-11 19:08:04

标签: c++ output cout

Edited

Hey guys I am making a small program to collect user input as a total then breaking it down into different taxes. I have the program set to have only two numbers after the decimal using setprecision. I am wondering if there is a way to make sure no matter what number is entered it is always aligned by its last decimal so it forms a perfect column? Right now if you run the program the numbers are right aligned but since the taxes generated are smaller, they don't line up underneath each other correctly. Any help would be appreciated.

To be more specific: No matter how many figures the "Total Collected" input is, for example four ($2,500) or five ($25,000), I am wanting the answers generated by my program to align properly still. I know setw can work but that is only if it is made to work for one type of number, such as five figure numbers.

Here is the code I am using via XCode:

#include <cstdlib>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main()

{
    string M;
    int Y;
    double T;
    double S;
    double C;
    double A;
    double O;


    cout << "Month: ";
    cin >> M;

    cout << "Year: ";
    cin >> Y;

    cout << "-----------------------------------\n";

    cout << "Total Collected:          $";
    cin >> T;

    S = (T / 1.06);
    C = (S * .02);
    A = (S * .04);
    O = (C + A);

    cout << "Sales:                    $" << right << setprecision(2) << fixed << S;
    cout << "\n";

    cout << "County Sales Tax:         $" << right << setprecision(2) << fixed << C;
    cout << "\n";

    cout << "State Sales Tax:          $" << right << setprecision(2) << fixed << A;
    cout << "\n";

    cout << "Total Sales Tax:          $" << right << setprecision(2) << fixed << O;
    cout << "\n";







    //std::system("pause");
    return 0;
} 

0 个答案:

没有答案