Float formatting in C++

夙愿已清 提交于 2019-11-27 15:01:33

You need to include <iomanip> and provide namespace scope to setw and setprecision

#include <iomanip>
std::setw(2)
std::setprecision(5)

try:

cout.precision(5);
cout << "Total : " << setw(4)   << floor(total*100)/100 << endl;

or

 cout << "Total : " << setw(4)   << ceil(total*10)/10 << endl;

iostream provides precision function, but to use setw, you may need to include extra header file.

Jon Spencer

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 <iostream>

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.

To also include the trailing zero, it isn't sufficient to set the precision. You also have to change the floating point format to fixed format, which uses the number of digits as told by setprecision as the number of digits after the decimal point:

std::cout << std::fixed << std::setprecision(2) << v;

Working online example code

Rapptz

If you want the trailing zero from rounding, you can use the C function printf.

#include <iostream>
#include <cstdio>

int main() {
    float v = 12.3961;
    std::printf("%.2f",v); //prints 12.40
}

Compared to:

#include <iostream>
#include <iomanip>

int main() {
    float v = 12.3961;
    std::cout << std::setprecision(4) << v; //prints 12.4
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!