Float formatting in C++

后端 未结 5 1537
感情败类
感情败类 2020-12-03 13:59

How do you format a float in C++ to output to two decimal places rounded up? I\'m having no luck with setw and setprecision as my compiler just tel

5条回答
  •  星月不相逢
    2020-12-03 14:34

    Use cout << fixed or cout.setf(ios::fixed), and std::cout.precision(<# of decimal digits>) as in the following (using the Clang-503.0.40 compiler included with OSX Mavericks):

    #include 
    
    int main()
    {
       using namespace std;
    
       float loge = 2.718;
       double fake = 1234567.818;
       cout << fixed;
       cout.precision(2);
       cout << "loge(2) = " << loge << endl;
       cout << "fake(2) = " << fake << endl;
       cout.precision(3);
       cout << "loge(3) = " << loge << endl;
       cout << "fake(3) = " << fake << endl;
    }
    

    The output from this is (note the rounding):

    loge(2) = 2.72
    fake(2) = 1234567.82
    loge(3) = 2.718
    fake(3) = 1234567.818
    

    This is the simple version. In lieu of using cout << fixed;, you can use cout.setf(ios::fixed); (for displaying scientific notation, replace fixed with scientific; both will set the number of digits to the right of the decimal point). Note the cout.precision() is also used to set the number of digits displayed in total on either side of the decimal point if the format flags do not include fixed or scientific. There are tutorials for this on the Internet.

提交回复
热议问题