如何正确格式化c++浮点数到小数点后两位

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

本文关键字:两位 小数点 格式化 何正确 c++ 浮点数      更新时间:2023-10-16

我使用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;
}

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

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

参见std::fixed和std::setprecision

使用流操纵符:

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