Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top