在 C++ 中显示带有填充和固定位数的数字

aar*_*rkk 2 c++ iostream iomanip

我想使用填充(如有必要)和固定数量的数字来显示数字。例如,给定以下数字:

48.3
0.3485
5.2
Run Code Online (Sandbox Code Playgroud)

像这样显示它们:

48.30
00.35
05.20
Run Code Online (Sandbox Code Playgroud)

我正在尝试 std::fixed、std::fill、std::setw 和 std::setprecision 的组合,但我似乎无法得到我正在寻找的东西。希望得到一些指导!

注意:0 填充并不是很重要,但我仍然希望数字对齐,以便小数点在同一列中。

joh*_*ohn 5

这很简单

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    cout << fixed << setprecision(2) << setfill('0');
    cout << setw(5) << 48.3 << endl;
    cout << setw(5) << 0.3485 << endl;
    cout << setw(5) << 5.2 << endl;
}
Run Code Online (Sandbox Code Playgroud)

printf然而,编写这样的代码让我渴望。