C++中的浮点格式化

eve*_*veo 17 c++ floating-point cout

如何在C++中格式化浮点数以输出四舍五入的小数位?我有没有运气setw,并setprecision为我的编译器只是告诉我,他们是not defined.

cout << "Total : " << setw(2) << total << endl;

总产出: Total : 12.3961

我希望它是:12.40或者12.39如果要完成这项工作太多了.

bil*_*llz 17

您需要包含<iomanip>并提供命名空间范围setw and setprecision

#include <iomanip>
std::setw(2)
std::setprecision(5)
Run Code Online (Sandbox Code Playgroud)

尝试:

cout.precision(5);
cout << "Total : " << setw(4)   << floor(total*100)/100 << endl;
Run Code Online (Sandbox Code Playgroud)

要么

 cout << "Total : " << setw(4)   << ceil(total*10)/10 << endl;
Run Code Online (Sandbox Code Playgroud)

iostream提供精确功能,但要使用setw,您可能需要包含额外的头文件.

  • @eveo这个(`12`而不是`12.39`)是因为`setprecision`定义了(默认)*有效*数字的数量,而不是小数点后的数字.请注意,对于较大的值,它将使用指数形式.如果你总是希望在小数点后面有两位数,就像我的情况一样,你必须使用固定数字格式(也写'std :: fixed`到`std :: cout`); 通过在线视图查看我的回答. (3认同)

Jon*_*cer 17

使用cout << fixedcout.setf(ios::fixed),std::cout.precision(<# of decimal digits>)如下所示(使用OSX Mavericks附带的Clang-503.0.40编译器):

#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;
}
Run Code Online (Sandbox Code Playgroud)

这个输出是(注意四舍五入):

loge(2) = 2.72
fake(2) = 1234567.82
loge(3) = 2.718
fake(3) = 1234567.818
Run Code Online (Sandbox Code Playgroud)

这是简单的版本.代替使用cout << fixed;,你可以使用cout.setf(ios::fixed);(用于显示科学记数法,用科学替换固定 ;两者都将设置小数点右边的位数).请注意,如果格式标志不包含fixedscientific,则cout.precision()也用于设置小数点两侧的总计显示的位数.互联网上有这方面的教程.


lee*_*mes 13

要包括尾随零,仅设置精度是不够的.您还必须将浮点格式更改为固定格式,它使用小数点后面的位数setprecision来表示的位数:

std::cout << std::fixed << std::setprecision(2) << v;
Run Code Online (Sandbox Code Playgroud)

在线工作示例代码

  • 为此,您需要将其添加到您的包含:#include <iomanip> (4认同)

vit*_*aut 7

您可以使用 C++20 来做到这一点std::format

std::cout << std::format("Total     : {:.2f}\n", total);
Run Code Online (Sandbox Code Playgroud)

fmt::format来自{fmt} 库的函数,std::format基于。{fmt} 还提供了print集成格式化和输出的功能,使其更加简单和高效(godbolt):

#include <fmt/core.h>

int main() {
  fmt::print("Total     : {:.2f}\n", 12.3961);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Total     : 12.40
Run Code Online (Sandbox Code Playgroud)

这使用 IEEE754 默认舍入模式(舍入到最接近的偶数),因此您必须自行舍入(How do I round up/down adecimal place of a float value? C++)。


Rap*_*ptz 6

如果您想要四舍五入的尾随零,您可以使用 C 函数printf

#include <iostream>
#include <cstdio>

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

相比:

#include <iostream>
#include <iomanip>

int main() {
    float v = 12.3961;
    std::cout << std::setprecision(4) << v; //prints 12.4
}
Run Code Online (Sandbox Code Playgroud)

  • @leemes 是的,我也不喜欢使用 C 函数,但在我看来,对于格式化的浮点输入,它比 `std::setprecision` 好得多。 (2认同)