Leon Anavi
IT Tips && Tricks

C/C++

Created: 13.10.2009 22:40 Last Modified: 17.10.2009 00:09 Views: 10869
Keywords: cout, fixed, precision, scientific, setfill, setw

Output Manipulations of Numbers with cout

Old School

To write numbers on the screen using the programming language C should be used functions printf and sprintf in order to convert number to sequence of characters. C++ introduces streams and cout to print any kind of data.

How to Print Numbers with cout

Scientific Notation

Scientific notation is also called standard form or exponential notation. It is used to represent number that are too large or small to be written with decimal notation. Number using scientific notation should be presented regarding the following formula:
ax10b

To force cout to print numbers with scientific notation use scientific of namespace std.

Fixed-point Notation

In order not to use scientific notation for presentation of the numbers fixed of namespace std should be used.

Decimal Presicion

Working with variables of floating-point type (float, double, etc.) may require specific precision of the output. Use function precesion to get or set the precision of cout. An argument of type streamsize must be passed to the function to set a new value for the floating-point precision.

Field Width

The field width determines the minimum number of characters to be printed. If the length of the text is shorted than the field width then text will be filled with specific character. The character can be set using setfill. By default the character is a space. Call setw to set field width and ios_base::width to get the current field width.

Examples

Source Code

#include <iostream>
#include <iomanip>

int main(int argc, char** argv)
{
	float nVar = 10.95;
	//standart output as dec
	std::cout << nVar << std::endl;
	//number with leading spaces if number of characters is less than 10
	std::cout << std::setw(10) << nVar << std::endl; 
	//scientific representation
	std::cout << std::scientific << nVar << std::endl;
	//Precision is set to 0, so the value of nVar will be printed as 11
	std::cout.precision(0);
	std::cout << std::fixed << nVar << std::endl;
	return 0;
}

Output

[leon@localhost couttest]$ g++ main.cpp -Wall -o couttest
[leon@localhost couttest]$ ./couttest
10.95
     10.95
1.095000e+01
11

Further Reading

Standard output stream
Get/Set floating-point decimal precision
Set field width
Set fill character
Use fixed-point notation
Use scientific notation


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.