如何正确地将C ++浮点数格式化为两位小数?

时间:2015-09-19 03:59:01

标签: c++ visual-c++ string-formatting

我在使用setprecision时遇到了一些问题。我不明白它是如何完全运作的。我搜索了这个问题,并能够推断出一些应该有效的代码。我不明白为什么不是。谢谢你的帮助,我还是有点新意。

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

2 个答案:

答案 0 :(得分:1)

如果要格式化浮点数以在C ++流中显示2个小数位,您可以轻松地:

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

请参阅std::fixedstd::setprecision

答案 1 :(得分:1)

使用流操纵器:

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