If you know the precision, then you just need to find the number with the most digits in the integral part:
100.2345
^^^
3
We can accomplish this with log10
. So for each number you have, check if it's negative (need to add an extra to the offset because of the minus sign) or positive and store the max offset as you go along.
For example:
double nums[]{ -10.2345, 100.2345, 10.2345, 1000.23456 };
int offset = INT_MIN;
int m{ 0 };
for (auto const& i : nums) {
if (i < 0)
m = log10(abs(i)) + 2;
else
m = log10(i) + 1;
if (m > offset) offset = m;
}
Now you have the offset, but you were dealing with a chosen precision; add this to the offset:
int precision = 2;
offset += precision + 1;
And voilà:
for (auto const& i : nums) {
cout << setprecision(precision) << fixed << setw(offset) << right << i
<< '\n';
}
Output:
-10.23
100.23
10.23
1000.23