Skill Level: Intermediate
I am sure many of you are familiar with the venerable printf()
function in C. However, using the cout
(standard output stream) object from the iostream
standard library is the preferred method for printing in C++. Most programmers quickly pick up the basics of using cout
, but often get tripped up when trying to format floating point numbers. I thought I would share how that can be accomplished with a simple example.
Since C++ is generally a superset of C, technically you can continue using the printf()
function in the same fashion in C++ that you are accustomed to in C. Nonetheless, cout
is still the preferred approach due to better type safety and extensibility over printf()
.
By default, cout
prints six significant digits of a floating point number, regardless of where the decimal point falls. The setprecision()
function is used to change the number of significant digits. Adding the fixed
manipulator changes the precision setting to apply specifically to the number of decimal places after the decimal point. Lastly, the setw()
function sets the minimum width of a field and adds extra padding when necessary.
The example C++ code shown below illustrates how to use both methods, printf()
and cout
, to print formatted floating point numbers with a field width of 5
and the number of decimal places set to 2
.
#include <iomanip> // std::setprecision, std::setw #include <iostream> // std::cout, std::fixed int main() { float floatA = 3.14159; float floatB = 12.3456; // Standard C formatting method printf("floatA = %5.2f\n", floatA); printf("floatB = %5.2f\n", floatB); std::cout << "==============" << '\n'; // separator // Preferred C++ formatting method std::cout << std::fixed // fix the number of decimal digits << std::setprecision(2); // to 2 std::cout << "floatA = " << std::setw(5) << floatA << '\n'; std::cout << "floatB = " << std::setw(5) << floatB << std::endl; }
The output of the program is shown below.
floatA = 3.14 floatB = 12.35 ============== floatA = 3.14 floatB = 12.35
Leave a Comment