0

I'm having some issues using setprecision. I don't understand how it works completely. I searched the problem and was able to extrapolate some code that should've worked. I don't understand why it's not. Thank you for your help, I'm still kind of new at this.

//monthly paycheck.cpp
//Paycheck Calculator
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main() {

    //Constants
    const double
        FEDERAL_TAX = 0.15,         //Federal Tax
        STATE_TAX = 0.035,          //State Tax
        SSA_TAX = 0.085,            //Social Security & Medicare
        HEALTH_INSURANCE = 75;      //Health Insurance

    //Variables
    int year;
    double grossAmount;
    string employeeName, month;

    // Initialize variables with input
    cout << "Hello, what's your first name? ";
    cin >> employeeName;

    cout << "What is your gross amount? ";
    cin >> grossAmount;

    cout << "Please enter the month and year: ";
    cin >> month >> year;

    // Output

    cout << "***********************************" << endl;
    cout << "Paycheck" << endl;
    cout << "Month: " << month << "\tYear: " << year << endl;
    cout << "Employee Name: " << employeeName << endl;
    cout << "***********************************" << endl;
    cout << setprecision(5) << fixed;
    cout << "Gross Amount: $" << grossAmount << endl;
    cout << "Federal Tax: $" << FEDERAL_TAX*grossAmount << endl;
    cout << "State Tax: $"  << STATE_TAX*grossAmount << endl;
    cout << "Social Sec / Medicare: $" << SSA_TAX*grossAmount << endl;
    cout << "Health Insurance: $" << HEALTH_INSURANCE << endl << endl;

    cout << "Net Amount: $" << fixed << grossAmount-grossAmount*(FEDERAL_TAX+STATE_TAX+SSA_TAX)-HEALTH_INSURANCE << endl << endl;

    system("PAUSE");
    return 0;
}
Omar
  • 21
  • 1
  • 1
  • 3
    Have you tried googling "How do I properly format C++ floats to two decimal places?" which brings up stuff like http://stackoverflow.com/questions/14432043/c-float-formatting and http://stackoverflow.com/questions/14596236/rounding-to-2-decimal-points – TheUndeadFish Sep 19 '15 at 04:24
  • If you want 2 decimal places, why do you `setprecision(5)`? – The Paramagnetic Croissant Sep 19 '15 at 05:41

2 Answers2

1

If you want to format floats to display with 2 decimal places in C++ streams, you could easily:

float a = 5.1258f;
std::cout << std::fixed << std::setprecision(2) << a << std::endl;

See std::fixed and std::setprecision

yaqwsx
  • 569
  • 1
  • 5
  • 14
1

Use stream manipulators:

std::cout.fixed;
std::cout.precision(Number_of_digits_after_the_decimal_point);
Ziezi
  • 6,375
  • 3
  • 39
  • 49