Right Justified Numeric Output

vegaseat 2 Tallied Votes 194 Views Share

An example how to line up your decimal points in a column like output of floating point numbers. Both C and C++ versions are shown. Thanks are given to Bud Tugly, my 77 year old senior student.

// right justified numeric output  (Dev-C++)

#include <cstdlib>
#include <iostream>
#include <cstdio>      // for printf()
#include <iomanip>     // setXXX() functions

using namespace std;

int main()
{
  double d1 = 30.768;
  double d2 = 1.345;
  double d3 = .430;
  
  // this works well, the decimal points line up
  printf("%8.3f\n",d1);
  printf("%8.3f\n",d2);
  printf("%8.3f\n\n",d3); 

  // dito, but keep the order of setXXX() functions!!
  cout << setiosflags(ios::fixed);
  cout << setw(8) << setprecision(3) << d1 << endl;
  cout << setw(8) << setprecision(3) << d2 << endl; 
  cout << setw(8) << setprecision(3) << d3 << endl << endl; 
    
  system("PAUSE");
  return EXIT_SUCCESS;
}
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Bud is convinced that programming keeps his brain sharp and keeps Alzheimer's away!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.