Display numbers with padding and a fixed number of digits in C++

aardvarkk picture aardvarkk · Apr 27, 2013 · Viewed 7.4k times · Source

I'd like to display numbers using a padding (if necessary) and a fixed number of digits. For instance, given the following numbers:

48.3
0.3485
5.2

Display them like this:

48.30
00.35
05.20

I'm trying combinations of std::fixed, std::fill, std::setw, and std::setprecision, but I can't seem to get what I'm looking for. Would love some guidance!

NOTE: The 0-padding isn't really critical, but I'd still like the numbers to be aligned such that the decimal point is in the same column.

Answer

john picture john · Apr 27, 2013

It's pretty straightforward

#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;
}

Writing code like this makes me yearn for printf however.