A couple of comments have mentioned std::setfill('0')
and std::setw
. While these are necessary, they're not sufficient to the task. For example, this code:
std::cout << std::setfill('0') << std::setw(7) << std::showpos << 0.012;
will produce: 0+0.012
as its output. This is obviously not quite what we wanted.
We need to add the std::internal
flag to tell the stream to insert "internal padding" -- i.e., the padding should be inserted between the sign and the rest of the number, so code like this:
std::cout << std::setfill('0') << std::setw(7) << std::internal << std::showpos << 0.012;
...produces the output we want: +00.012
.
Also note that the padding character is "sticky", so if you alternate between using std::setw
with numeric and non-numeric types, you'll probably need/want to change it each time. Otherwise, something like std::cout << setw(12) << name;
will produce results like: 0000000Jerry
, which is rarely desired either.
To assure that we always get the same number of places after the decimal point, we also need to set the std::fixed
flag, and specify the number of places with std::setprecision
, such as:
#include <iostream>
#include <iomanip>
#include <vector>
int main() {
std::vector<double> values { 0.1234, 1.234, 1.5555 };
for (auto d : values)
std::cout << std::internal << std::showpos << std::setw(9)
<< std::setprecision(3) << std::setfill('0') << d << "\n";
}
Which produces the output I believe is desired:
+0000.123
+0001.234
+0001.556
There is one circumstance under which you won't get aligned results this way though: if you have a number too large to fit into the field provided, all the places before the decimal point will still be printed. For example, if we added 1e10
to the list of numbers to be printed by the preceding code, it would be printed out as: +10000000000.000
, which obviously won't align with the rest.
The obvious way to deal with that would be to just put up with it, and if it arises often enough to care about, increase the field size to accommodate the larger numbers.
Another possibility would be to use fixed notation only the number is below a certain threshold, and switch to (for example) scientific notation for larger numbers.
At least in my experience, code like this tends to be used primarily for financial data, in which case the latter option usually isn't acceptable though.