如何在使用cout<<时使用前导零填充浮点数?操作者

时间:2014-03-19 15:04:20

标签: c++ cout

把这些问题放在一起:

How can I pad an int with leading zeros when using cout << operator?

Printing the correct number of decimal points with cout

如何流式传输到std :: cout,例如,此变量

double x = 7.1224

让它看起来像这样?

07.12

1 个答案:

答案 0 :(得分:6)

结合std::setwstd::setfillstd::fixedstd::setprecision

std::cout << std::setfill('0') << std::setw(5) 
          << std::fixed << std::setprecision(2) << x;

因此,setw的值为:2表示所需的精度+ 2表示所需的整数+ 2表示浮点数。

注意:x = 107.1224将输出为107.12

相关问题