1

How do I align the code to 3 places to the right instead of the default left?

10.23   
100.23

 10.23 ----------Like this
100.23  


double test = 10.2345;
double test2 =100.2345;

std::cout << std::setprecision(2) << std::fixed << test << '\n' << test2 << std::endl;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Daboss2182
  • 25
  • 5
  • Use `std::right` from `` https://en.cppreference.com/w/cpp/io/manip/left and `std::setw` https://en.cppreference.com/w/cpp/io/manip/setw – JohnFilleau Jun 29 '20 at 00:11
  • See [C++ cout decimal alignment](https://stackoverflow.com/questions/25936009/c-cout-decimal-alignment). – dxiv Jun 29 '20 at 00:13
  • @dxiv I have tried the above setw and right but dont seem to work cout << "test " << setw(3) << fixed << setprecision(2) << left << test << endl; cout << "test " << setw(3) << fixed << setprecision(2) << left << test2 << endl; – Daboss2182 Jun 29 '20 at 00:20
  • @Daboss2182 Your numbers would need a width >= 6. – dxiv Jun 29 '20 at 00:28

2 Answers2

0

Set the width of the output first using std::cout.width(num); and setting the output to the right using std::right, something like this:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout.width(6);
    std::cout << std::right << 10.23 << std::endl;
    std::cout << std::right << 10.453;

    return 0;
}
0

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
Andreas DM
  • 10,685
  • 6
  • 35
  • 62