简体   繁体   中英

How do I properly format C++ floats to two decimal places?

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;
}

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

Use stream manipulators:

std::cout.fixed;
std::cout.precision(Number_of_digits_after_the_decimal_point);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM