4

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.

aardvarkk
  • 14,955
  • 7
  • 67
  • 96

1 Answers1

7

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.

john
  • 85,011
  • 4
  • 57
  • 81
  • This breaks if setprecision goes too high. Does setw have to be greater than setprecision + 3 or something? – aardvarkk Apr 27 '13 at 04:50
  • If you want two leading digits and a decimal point then yes, setw must be >= setprecision + 3. – john Apr 27 '13 at 04:54
  • As an additional note, I think a big problem was that I was (earlier in the line) setting the alignment with `std::left`. That also messes up this solution, so I had to make sure to set it back to `std::right` for this to work. – aardvarkk May 03 '13 at 16:46
  • While it does make me miss `printf` I like the C++ way because I can apply this to a `stringstream` and get the output as `string` – Everyone Dec 03 '17 at 17:56