如何在cout<<中获得十进制后的固定数字

C++ How to get fixed digit after decimal in cout<<

本文关键字:数字 十进制 cout      更新时间:2023-10-16

c++如何在输出中获得十进制后的固定数字????像f = 123.456789我想在输出中显示123.46

可以在c++中使用setprecision()方法。

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

另一种方法是使用printf函数,确保您包含stdio.h文件来使用它,
printf (" % 0.2 f, f);
这里%f是格式说明符(float), '%'和'f'之间的0.2用于将精度设置为小数点后两位。

您也可以使用boost::format

#include <boost/format.hpp>
cout << boost::format("%.2f") % f << endl;

您需要I/O操纵符来实现十进制精度。

#include <iomanip>
#include <iostream>
int main( )
{
    double foo = 123.456789L;
    std::cout << std::setprecision(2) << std::fixed << foo << std::endl;
    return 0;
}