Showing posts with label Print Formatting. Show all posts
Showing posts with label Print Formatting. Show all posts

Wednesday, 10 March 2010

Fixed form, Scientific form and Precision setting for floating point numbers

Sometimes we want to output the floating point numbers in fixed or scientific form and sometimes with fixed precision so as to align all the output. The following program is an example to demonstrate that:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows how to output floating point numbersin fixed and
#include<iostream>

using namespace
std;

int
main()
{

float
number = 123.456;

cout << "number in fixed form = " << number << endl; //default is fixed
cout << "number in scientific form = " << scientific << number << endl;
cout.precision(2);
cout << "number in fixed form with precision 2 = " << fixed << number << endl; //here the format was scientific
cout.precision(3);
cout << "number in fixed form with precision 3 = " << number << endl;
cout.precision(4);
cout << "number in fixed form with precision 4 = " << number << endl;
cout.precision(5);
cout << "number in fixed form with precision 5 = " << number << endl;

return
0;
}






The output is as follows:

Wednesday, 3 March 2010

Printing out leading 0's (or any other charachters)

This is a simple example to print out leading zeroes or any charachters when printing out numbers. The main manipulator function needed is the set field width that will set the width of the field.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows how to print leading 0's in the output

#include<iostream>
#include<iomanip>

using namespace
std;

int
main()
{

int
number = 123;

cout<< "number = "<< number << endl;

cout<< "number = "<< setw(2) << setfill('0') << number << endl;
cout<< "number = "<< setw(3) << setfill('0') << number << endl;
cout<< "number = "<< setw(4) << setfill('0') << number << endl;
cout<< "number = "<< setw(5) << setfill('0') << number << endl;
cout<< "number = "<< setw(10) << setfill('0') << number << endl;

cout<< endl;
cout<< "number = "<< setw(5) << setfill('x') << number << endl;

cout<< endl;
number = 0;
cout<< "number = "<< setw(5) << setfill('x') << number << endl;

return
0;
}







The output is as follows: